// packageD/directSeeding/livePage/livePage.js
let app = getApp();
let clicktag = 0;
const queue = {};
let timer = 0;
let timer_1 = 0;
let timer_2 = null;
let timer_3 = null;
let timer_4 = 0;
// let activityTime = null;
let ctx = null;
let myCanvasWidth = null;
let myCanvasHeight = null;
let unit = "";
let canvasDpr = 1;
import TIM from "../../tim-wx-sdk/tim-wx";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    isShowADLook: true, //广告列表按钮
    isShowADPut: true, //广告投放按钮
    close_reward: 0, //是否关闭打赏，1是，0否
    close_chat: 0, //是否关闭评论，1是，0否
    giftEffectsTime: null, //打赏特效定时器
    specialList: [], //打赏特效
    language: "",
    inputInfo: "",
    statusBarHeight: 0,
    navBarHeight: 0,
    showUser: false,
    shade: false,
    showGoodLift: false,
    showGift: false,
    showactivity: false,
    showavticeFail: false,
    mainCommentShow: false,
    style_img: "",
    width: 60,
    height: 260,
    //公告栏效果
    tipsContentHeight: 0,
    tipsContent: [],
    tipsContentMsssage: "",
    tipsopacity: 0,
    tipsopacityBol: false,
    //礼物滚动
    widthAll: 0,
    giftScreenLeft: 0,
    giftwidth: 0,
    giftScreenLeftBol: true,
    firstwidth: "",
    activeNum: "",
    giftListContent: [],
    giftListmessage: {},
    //是否关注
    focusBol: true,
    // followSuccessBol: false,
    //礼物选择
    giftSelectId: "",
    giftListData: "",
    giftSelectNUm: 0,
    //
    roomData: "",
    giftMemberData: "",
    id: "",
    room_id: "",
    postData: {},
    anchorPopupData: "",
    //
    heightauto: "auto",
    widthauto: "auto",
    screeheight: "",
    //直播类型
    playerType: "live",
    //滑动列表
    liveListData: [],
    backid: "",
    last_room_id: "",
    last_backid: "",
    //more
    isLoadMore: true,
    page: 1,
    total_page: 0,
    //营销活动
    activityData: "",
    lasttime: "",
    activityTimeArray: [],
    activityDataArray: [],
    //消息列表
    messageList: [],
    messagesTop: 0,
    view_num: 0,
    giftSelectBol: false,
    roomMemberContent: [],
    roomMemberContentArray: [],
    roomMemberTimeArray: [],
    playBackUrl: "plugin.room.frontend.live-list.play-back",
    memberid: "",
    loadingImg: true,
    loadingMessage: "海报生成中",
    tim: "",
    shownum: 0,
    likeNumBol: true,
    lastGroupId: "",
    pauseBol: true,
    catMessagebol: true,
    wechatpayShow: false,
    roomObj: "",
    usewechatpayBol: false,
    moreShowBol: false,
    memberBol: false,
    room_ban: false,
    explainingGoods: {
      goods_id: "",
    },
    commoditiesshow: true,
    picturemodeshow: true,
    imReadly: true,
    sendMessageReadly: true,
    SDKAppID: "",
    activityDataBtnBol: false,
    roomMemberBtnBol: false,
    permissionsShow: true,
    passwordShow: false,
    passwordVal: "",
    passwordIndex: undefined,
    IMmessage: {},
    changeAnchor: true, //滑动改变直播间时
    luck_number: 0,

    showPosterWord: false,
    diyPosterWord: "",
    oldWord:'',
    chatInputBottom:0,//键盘弹起时，input高度问题

    isLivePK: false,
    livePKData:{},
    livePKSrc:'',
    startPKTime: null,
    pkTimer: null,
    PKTimed: "00:00:00", //连麦已进行的时长
    mode_button: 1, //0为竖屏，1为横屏
    // 观看时长定时器
    rewardTimeOut:null,
    // 推广id
    code_id:'',
    // 直播进入小窗
    smallWindowIn:false
  },

  gotoFanList() {
    wx.navigateTo({
      url:
        "/packageD/directSeeding/liveFanList/liveFanList?memberId=" +
        this.data.id,
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    setTimeout(function () {
      wx.hideLoading();
    }, 10000);
    setTimeout(function () {
      that.data.imReadly = false;
      that.data.sendMessageReadly = false;
    }, 5000);
    this.setData({
      code_id:null
    });
    // console.log('重新启动清除一下推广id',this.data.code_id)
    if (options.scene) {
      let scene = decodeURIComponent(options.scene);
      if (scene) {
        var info_arr = [];
        info_arr = scene.split(",");
        for (let i = 0; i < info_arr.length; i++) {
          let chil_arr = [];
          chil_arr = info_arr[i].split("=");
          if (chil_arr[0] == "id") {
            this.setData({
              room_id: chil_arr[1],
            });
          } else if (chil_arr[0] == "pT") {
            this.setData({
              playerType: chil_arr[1],
            });
          } else if (chil_arr[0] == "bid") {
            this.setData({
              backid: chil_arr[1],
            });
          } else if (chil_arr[0] == "meid") {
            this.setData({
              memberid: chil_arr[1],
            });
          } else if (chil_arr[0] == "mid") {
            app._setMid(chil_arr[1]);
          } else if (chil_arr[0] == "cd") {
            this.setData({
              code_id : chil_arr[1]
            });
          }else if (chil_arr[0] == "T") {
            if (chil_arr[1] == 1) {
              this.setData({
                playerType: "live",
              });
            } else {
              this.setData({
                playerType: "video",
              });
            }
          } else if (chil_arr[0] == "D") {
            this.setData({
              memberBol: true,
            });
          }
        }
      }
    } else {
      if (options.mid) {
        app._setMid(options.mid);
        this.newMedia(4);
      }
      if (options.id) {
        this.setData({
          room_id: options.id,
        });
      }
      if(options.cd){
        this.setData({
          code_id:options.cd
        });
      }
      //判断直播类型是回放还是直播 live：直播 video：回放
      if (options.playerType) {
        this.setData({
          playerType: options.playerType,
        });
      }
      //回放id
      if (options.backid) {
        this.setData({
          backid: options.backid,
        });
      }
      if (options.memberid) {
        this.setData({
          memberid: options.memberid,
        });
      }
    }
    let { statusBarHeight, navBarHeight } = app.globalData;
    this.setData({
      statusBarHeight,
      navBarHeight,
    });
    this.getsdkappid();
    this.newMedia(3);
    //创建点赞动画标签
    // this.getGiftEffect(); //开启礼物效果
    // this.getData(); //获取数据
    // this.getPoster(); //加载海报
  },
  permissionsShowBtn() {
    this.setData({
      permissionsShow: !this.data.permissionsShow,
    });
  },
  passwordValInp(e) {
    let val = e.detail.value;
    this.setData({
      passwordVal: val,
    });
  },
  commoditiesclosebtn() {
    this.setData({
      commoditiesshow: false,
    });
  },
  getmoreBtn() {
    this.setData({
      moreShowBol: true,
    });
  },
  showShoplistBtn(e) {
    let index = e.currentTarget.dataset.index;
    this.setData({
      ["roomData.diy_menu[" + index + "].show"]: true,
    });
  },
  moreShowCloseBtn() {
    this.setData({
      moreShowBol: false,
    });
  },
  gooption(e) {
    let index = e.currentTarget.dataset.index;
    let url = this.data.roomData.diy_option[index].min_url;
    if (url) {
      try {
        wx.navigateTo({
          url: url,
        });
      } catch (e) {
        wx.showToast({
          title: "链接设置错误:" + url,
          icon: "none",
          duration: 2000,
        });
        //TODO handle the exception
      }
    } else {
      wx.showToast({
        title: "链接未设置",
        icon: "none",
        duration: 2000,
      });
    }
  },
  gomenu(e) {
    let index = e.currentTarget.dataset.index;
    let url = this.data.roomData.diy_menu[index].min_url;
    if (url) {
      try {
        wx.navigateTo({
          url: url,
        });
      } catch (e) {
        wx.showToast({
          title: "链接设置错误:" + url,
          icon: "none",
          duration: 2000,
        });
      }
    } else {
      wx.showToast({
        title: "链接未设置",
        icon: "none",
        duration: 2000,
      });
    }
  },
  usewechatpay() {
    var that = this;
    if (this.data.usewechatpayBol) {
      return false;
    }
    that.data.usewechatpayBol = true;
    let urlStr = app.getNetAddresss("finance.balance.recharge");
    if (!that.data.giftmoney) {
      wx.showToast({
        icon: "none",
        title: that.data.giftMemberData.credit2_name
          ? "充值" + that.data.giftMemberData.credit2_name + "不小于0"
          : "充值余额不小于0",
        duration: 1500,
      });
      that.setData({
        wechatpayShow: false,
      });
      return false;
    }
    urlStr += "&client_type=2";
    urlStr += "&app_type=wechat";
    urlStr += "&pay_type=1";
    urlStr += "&recharge_money=" + that.data.giftmoney;
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          var pay_data = res.data.config;
          var payParams = {
            timeStamp: pay_data.timestamp,
            nonceStr: pay_data.nonceStr,
            package: pay_data.package,
            signType: pay_data.signType,
            paySign: pay_data.paySign,
          };
          that.WXPay(payParams);
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
          that.setData({
            wechatpayShow: false,
          });
          that.data.usewechatpayBol = false;
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  WXPay(payParams) {
    let that = this;
    wx.requestPayment({
      timeStamp: payParams.timeStamp,
      nonceStr: payParams.nonceStr,
      package: payParams.package,
      signType: payParams.signType ? payParams.signType : "MD5",
      paySign: payParams.paySign,
      success: function (res) {
        that.giftwechatpay();
        that.data.usewechatpayBol = false;
      },
      fail: function (res) {
        wx.showToast({
          title: "支付失败请稍后重试",
          icon: "none",
          duration: 2000,
          success: function () {},
          fail: function () {},
        });
        that.data.usewechatpayBol = false;
      },
    });
  },
  wechatpayShowCloseBtn() {
    this.setData({
      wechatpayShow: false,
    });
  },
  giftwechatpay() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.room.frontend.reward.index");
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: {
        reward_type: this.data.activeNum,
        room_id: this.data.room_id,
        reward_id: this.data.giftSelectId,
        number: this.data.giftmoney,
      },
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          wx.showToast({
            icon: "none",
            title: "打赏成功",
            duration: 1500,
          });
          that.setData({
            wechatpayShow: false,
          });
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
        that.data.giftSelectBol = false;
      },
      fail: function (res) {
        console.log(res.msg);
      },
    });
  },
  getmemberid() {
    let that = this;
    let urlStr = app.getNetAddresss(
      "plugin.room.frontend.anchor.get-member-id"
    );
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: {
        room_id: this.data.room_id,
      },
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            memberid: res.data.member_id,
          });
          that.getplayBack();
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res.msg);
      },
    });
  },
  getsdkappid() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.room.frontend.im.get-im-sdk");
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: {},
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          let options = {
            SDKAppID: res.data.sdkappid, // 接入时需要将0替换为您的即时通信 IM 应用的 SDKAppID
          };
          if (res.data.sdkappid) {
            that.data.SDKAppID = res.data.sdkappid;
          }
          // 创建 SDK 实例，`TIM.create()`方法对于同一个 `SDKAppID` 只会返回同一份实例
          that.data.tim = TIM.create(options); // SDK 实例通常用 tim 表示
          that.data.tim.setLogLevel(0);
          that.chatEventList(); //加载聊天事件
          if (that.data.playerType == "live") {
            wx.showLoading({
              title: "直播加载中...",
            });
            that.data.roomObj = wx.createLivePlayerContext(
              "liveid_" + that.data.room_id
            );
            that.getLiveList();
          } else if (that.data.playerType == "video") {
            if (that.data.memberid || that.data.memberBol) {
              that.data.playBackUrl = "plugin.room.frontend.anchor.get-back";
              if (that.data.memberid) {
                that.getplayBack();
              } else {
                that.getmemberid();
              }
            } else {
              that.getplayBack();
            }
          }
          that.getinformation(); // 获取屏幕宽度
          that.getMyCanvasMessage(); // 获取海报画布宽高
          ctx = wx.createCanvasContext("bubble");
          that.getTipsContent(); //开启公告栏效果
          // that.getGiftList(); //获取礼物列表数据
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res.msg);
      },
    });
  },
  setGoods(e) {
    let that = this;
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url:
        "/packageA/detail_v2/detail_v2?id=" +
        id +
        "&liveshow=1&roomid=" +
        that.data.room_id,
    });
  },
  //记录进入直播间
  comeRoom() {
    if (this.data.IMmessage.come == 1) {
      this.catComeMessage();
    }
    if (this.data.IMmessage.welcome == 1) {
      this.catWelcomeMessage();
    }
  },
  //创建进入直播间自定义模版
  catComeMessage() {
    let that = this;
    let messageData = {};
    let Json = {
      memberId: this.data.roomData.userID ? this.data.roomData.userID : "",
      nickname: this.data.roomData.userNickname
        ? this.data.roomData.userNickname
        : "",
      memberAvatar: this.data.roomData.userAvatar
        ? this.data.roomData.userAvatar
        : "",
    };
    messageData = {
      to: that.data.roomData.groupId,
      conversationType: TIM.TYPES.CONV_GROUP,
      payload: {
        data: "自定义文本", // 用于标识该类型消息
        description: JSON.stringify(Json),
        extension: "come",
      },
    };

    let message = that.data.tim.createCustomMessage(messageData);
    let promise = that.data.tim.sendMessage(message);
    let tipsContent = that.data.tipsContent;
    promise
      .then(function (imResponse) {
        // 发送成功
        tipsContent.push({
          type: "come",
          nickname: Json.nickname,
        });
        that.data.tipsContent = tipsContent;
        console.log("xx进入直播间提示成功：：：");
      })
      .catch(function (imError) {
        // 发送失败
        wx.showToast({
          icon: "none",
          title: "进入直播间提示失败:::" + imError,
          duration: 1200,
        });
        console.warn("sendMessage error:", imError);
      });
  },
  //创建 进入直播间欢迎文字 自定义模版
  catWelcomeMessage() {
    let that = this;
    let messageData = {};
    let Json = {
      content: this.data.IMmessage.welcome_content,
    };
    messageData = {
      to: that.data.roomData.groupId,
      conversationType: TIM.TYPES.CONV_GROUP,
      payload: {
        data: "自定义文本", // 用于标识该类型消息
        description: JSON.stringify(Json),
        extension: "welcome",
      },
    };

    let message = that.data.tim.createCustomMessage(messageData);
    let promise = that.data.tim.sendMessage(message);
    let messageList = that.data.messageList;
    promise
      .then(function (imResponse) {
        // 发送成功
        messageList.push({
          content: Json.content,
        });
        that.setData({
          messageList,
          messagesTop: messageList.length * 1000,
        });
        console.log("进入直播间自动回复成功提示：：：");
      })
      .catch(function (imError) {
        // 发送失败
        wx.showToast({
          icon: "none",
          title: "进入直播间自动回复提示失败:::" + imError,
          duration: 1200,
        });
        console.warn("sendMessage error:", imError);
      });
  },
  activeRoomSet() {
    let that = this;
    if (this.data.IMmessage) {
      if (
        this.data.IMmessage.now_goods &&
        this.data.IMmessage.now_goods.goods_id
      ) {
        //当前讲解商品
        that.setData({
          explainingGoods: this.data.IMmessage.now_goods,
        });
      }
      if (this.data.IMmessage.room_ban == 1) {
        //禁入直播间
        that.setData({
          picturemodeshow: false,
        });
        wx.showModal({
          title: "提示",
          content: "您已被禁入直播间",
          showCancel: false,
          success(res) {
            if (res.confirm) {
              wx.redirectTo({
                url: "/packageD/directSeeding/liveList/liveList",
              });
            }
          },
        });
        return;
      }
      if (this.data.IMmessage.chat_ban == 1) {
        wx.showModal({
          title: "提示",
          content: "您已经被禁言",
          showCancel: false,
          success(res) {},
        });
        that.setData({
          room_ban: true,
        });
        return;
      }
    }
    //废弃，改为IM自定义模板发送信息
    // let urlStr = app.getNetAddresss("plugin.room.frontend.live.come-room");
    // app._postNetWork({
    // 	url: urlStr,
    // 	showToastIn: false,
    // 	data: {
    // 		room_id: that.data.room_id
    // 	},
    // 	success: function(resdata) {
    // 		var res = resdata.data;
    // 		if (res.result == 1) {
    // 			if (res.data.now_goods && res.data.now_goods.goods_id) {
    // 				that.setData({
    // 					explainingGoods: res.data.now_goods
    // 				})
    // 			}
    // 			if (res.data.room_ban == 1) {
    // 				that.setData({
    // 					picturemodeshow: false
    // 				})
    // 				wx.showModal({
    // 					title: '提示',
    // 					content: '您已被禁入直播间',
    // 					showCancel: false,
    // 					success(res) {
    // 						if (res.confirm) {
    // 							wx.redirectTo({
    // 								url: '/packageD/directSeeding/liveList/liveList'
    // 							})
    // 						}
    // 					}
    // 				})
    // 				return
    // 			}
    // 			if (res.data.chat_ban == 1) {
    // 				wx.showModal({
    // 					title: '提示',
    // 					content: '您已经被禁言',
    // 					showCancel: false,
    // 					success(res) {
    // 						if (res.confirm) {

    // 						}
    // 					}
    // 				})
    // 				that.setData({
    // 					room_ban: true
    // 				})
    // 				return
    // 			}
    // 		} else {

    // 		}
    // 	},
    // 	fail: function(res) {
    // 		console.log(res.msg)
    // 	}
    // });
  },
  getLiveList() {
    let that = this;
    let urlStr = app.getNetAddresss(
      "plugin.room.frontend.live-list.get-live-list"
    );
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: {
        status: 3,
        page: 1,
      },
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            total_page: res.data.last_page
          });
          let LiveListData = res.data.data;
          let LiveArray = [
            {
              id: that.data.room_id,
              changeloadBol: false,
            },
          ];
          if (LiveListData.length > 0) {
            LiveListData.forEach((x) => {
              if (x.id != that.data.room_id) {
                LiveArray.push({
                  id: x.id,
                  avatar: x.avatar,
                  banner: x.banner,
                  cover: x.cover,
                  changeloadBol: false,
                });
              }
            });
            that.setData({
              liveListData: LiveArray,
              last_room_id: that.data.room_id,
            });
          } else {
            that.setData({
              liveListData: [
                {
                  id: that.data.room_id,
                },
              ],
              last_room_id: that.data.room_id,
            });
          }
          that.getData(0); //获取数据
          that.getPoster(); //加载海报
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res.msg);
      },
    });
  },
  getplayBack() {
    let that = this;
    let urlStr = app.getNetAddresss(that.data.playBackUrl);
    let json = {};
    if (this.data.memberid) {
      json = {
        member_id: this.data.memberid,
        page: 1,
      };
    } else {
      json = {
        page: 1,
      };
    }
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: json,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            total_page: res.data.last_page,
          });
          let playBackData = res.data.data;
          let playBackArray = [
            {
              id: that.data.room_id,
              backid: that.data.backid,
              changeloadBol: false,
            },
          ];
          if (playBackData.length > 0) {
            playBackData.forEach((x) => {
              if (x.id != that.data.backid) {
                playBackArray.push({
                  id: x.room_id,
                  backid: x.id,
                  avatar: x.avatar,
                  banner: x.banner,
                  cover: x.cover,
                  changeloadBol: false,
                });
              }
            });
            that.setData({
              liveListData: playBackArray,
              last_backid: that.data.backid,
            });
          } else {
            that.setData({
              liveListData: [
                {
                  id: that.data.room_id,
                  backid: that.data.backid,
                },
              ],
              last_backid: that.data.backid,
            });
          }
          that.getBackData(0);
          that.getPoster(); //加载海报
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res.msg);
      },
    });
  },
  liveChange(e) {
    // 清理定时器
    this.data.rewardTimeOut = null;
    // console.log('clearInterval')
    clearInterval(this.data.rewardTimeOut);
    let realIndex = e.detail.current;
    console.log(realIndex);
    this.quitGroup();
    let that = this;
    that.setData({
      loadingImg: true,
      loadingMessage: "海报生成中",
    });
    if (realIndex == that.data.liveListData.length - 2) {
      that.getMoreData();
    }
    for (let i = 0; i < this.data.liveListData.length; i++) {
      that.setData({
        ["liveListData[" + i + "].changeloadBol"]: false,
      });
    }
    if (that.data.playerType == "live") {
      that.setData({
        room_id: that.data.liveListData[realIndex].id,
        changeAnchor: true,
        isLivePK: false,
        livePKData: {}
      });
      that.getData(realIndex); //获取数据
      // that.getAnchorPopup(); //加载主播弹窗数据
      that.getPoster(); //加载海报
      that.data.roomObj = wx.createLivePlayerContext(
        "liveid_" + that.data.room_id
      );
      if (this.data.pkTimer) {
        // console.log('clearInterval')
        clearInterval(this.data.pkTimer);
        this.data.pkTimer = null;
      }
    } else {
      that.setData({
        room_id: that.data.liveListData[realIndex].id,
        backid: that.data.liveListData[realIndex].backid,
        changeAnchor: true,
      });
      that.getBackData(realIndex); //获取数据
      // that.getAnchorPopup(); //加载主播弹窗数据
      that.getPoster(); //加载
    }
    //清除聊天
    that.setData({
      messageList: [],
      messagesTop: 0,
    });
    that.data.tipsContent = [];
    that.data.giftListContent = [];
    that.setData({
      tipsContentMsssage: "",
      giftListmessage: {},
    });
    that.data.catMessagebol = true;
    that.setData({
      likeNumBol: true,
    });
  },
  getBackData(index) {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.room.frontend.live.room-back");
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: {
        room_id: this.data.room_id,
        back_id: this.data.backid,
      },
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          console.log(res.data);
          that.setData({
            shownum: res.data.like_num ? res.data.like_num : 0,
            roomData: res.data,
            id: res.data.member_id,
            view_num: res.data.view_num,
            IMmessage: res.data.message,
            luck_number: res.data.luck_number || 0,
            close_reward: res.data.close_reward || 0,
            close_chat: res.data.close_chat || 0,
            mode_button: res.data.mode_button || 0
          });
          if (res.data.is_concern == 1) {
            that.setData({
              focusBol: false,
            });
          } else {
            that.setData({
              focusBol: true,
            });
          }
          that.activeRoomSet();
          if (res.data.IM == 1) {
            setTimeout(() => {
              that.chatLogin();
            }, 1000);
          }
          if (that.data.last_backid == that.data.backid) {
            that.setData({
              "liveListData[0].avatar": res.data.avatar,
              "liveListData[0].cover": res.data.cover,
              "liveListData[0].banner": res.data.banner,
            });
          }
          if (index !== undefined) {
            that.setData({
              ["liveListData[" + index + "].changeloadBol"]: true,
            });
          }
          // that.data.tipsContent = [];
          // that.data.giftListContent = [];
          // that.setData({
          // 	tipsContentMsssage: "",
          // 	giftListmessage: {}
          // })
          clearTimeout(timer_1);
          clearTimeout(timer_2);
          clearTimeout(timer_3);
          that.getGiftEffect(); //开启礼物效果
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res.msg);
      },
    });
  },
  getMoreData() {
    const that = this;
    let json = {};
    let api = "";
    let urlStr = "";
    that.data.isLoadMore = false; // 防止多次请求分页数据
    if (this.data.page >= this.data.total_page) {
      return;
    } else {
      this.data.page = this.data.page + 1;
      if (this.data.playerType == "live") {
        api = "plugin.room.frontend.live-list.get-live-list";
        json = {
          status: 3,
          page: this.data.page,
        };
      } else {
        api = that.data.playBackUrl;
        if (this.data.memberid) {
          json = {
            member_id: this.data.memberid,
            page: this.data.page,
          };
        } else {
          json = {
            page: this.data.page,
          };
        }
      }
      urlStr = app.getNetAddresss(api);
      app._postNetWork({
        url: urlStr,
        showToastIn: false,
        data: json,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            if (that.data.playerType == "live") {
              let LiveListData = res.data.data;
              let LiveArray = that.data.liveListData;
              if (LiveListData.length > 0) {
                LiveListData.forEach((x) => {
                  if (x.id != that.data.last_room_id) {
                    LiveArray.push({
                      id: x.id,
                      avatar: x.avatar,
                      banner: x.banner,
                      cover: x.cover,
                      changeloadBol: false,
                    });
                  }
                });
                that.setData({
                  liveListData: LiveArray,
                });
              }
            } else {
              let playBackData = res.data.data;
              let playBackArray = that.data.liveListData;
              if (playBackData.length > 0) {
                playBackData.forEach((x) => {
                  if (x.id != that.data.last_backid) {
                    playBackArray.push({
                      id: x.room_id,
                      backid: x.id,
                      avatar: x.avatar,
                      banner: x.banner,
                      changeloadBol: false,
                    });
                  }
                });
                that.setData({
                  liveListData: playBackArray,
                });
              }
            }
          } else {
            that.setData({
              page: that.data.page - 1,
              isLoadMore: false,
            });
            return;
          }
        },
        fail: function (res) {
          console.log(res.msg);
        },
      });
    }
  },
  // 获取屏幕宽度
  getinformation() {
    try {
      const res = wx.getSystemInfoSync();
      let windowHeight = res.windowHeight;
      let windowWidth = res.windowWidth;
      this.setData({
        heightauto: windowHeight + "px",
        widthauto: windowWidth + "px",
      });
      this.data.screeheight = windowHeight;
    } catch (e) {
      // Do something when catch error
    }
  },
  //购物公告栏效果
  getTipsContent() {
    this.startMove();
  },
  //礼物效果
  getGiftEffect() {
    let that = this;
    const gift = wx.createSelectorQuery();
    gift.selectAll("#gift_screen .li").boundingClientRect();
    gift.selectViewport().scrollOffset();
    gift.exec(function (res) {
      let widthAll = 0;
      let widthArray = res[0] ? res[0] : [];
      widthArray.forEach(function (item, index) {
        widthAll += item.width;
      });
      that.data.firstwidth = widthArray[0].width;
      const giftwidth = wx.createSelectorQuery();
      giftwidth.select("#gift_screen").boundingClientRect();
      giftwidth.selectViewport().scrollOffset();
      giftwidth.exec(function (res) {
        let width = res[0].width;
        that.setData({
          giftwidth: width,
          widthAll: widthAll < width ? width : widthAll,
          giftScreenLeft: width,
        });
        timer_3 = setTimeout(() => {
          that.setData({
            giftScreenLeftBol: false,
          });
          that.giftListRoll();
        }, 1000);
      });
    });
  },
  // 获取海报画布宽高
  getMyCanvasMessage() {
    wx.getSystemInfo({
      success: (res) => {
        canvasDpr = wx.getSystemInfoSync().pixelRatio;
        if (res.windowWidth * 2 < 750) {
          unit = res.windowWidth / 620;
        } else {
          unit = res.windowWidth / 750;
        }
        myCanvasWidth = 620 * canvasDpr * unit;
        myCanvasHeight = 883 * canvasDpr * unit;
        this.setData({
          canvasWidth: parseInt(myCanvasWidth),
          canvasHeight: parseInt(myCanvasHeight),
        });
      },
    });
  },
  //主播弹窗数据
  getAnchorPopup() {
    // 防止多次请求
    if (clicktag == 0) {
      clicktag = 1;
      setTimeout(function () {
        clicktag = 0;
      }, 2000);
    }
    wx.showLoading({
      title: "加载中",
    });
    let that = this;
    let urlStr = app.getNetAddresss("plugin.room.frontend.live.anchor-popup");
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: {
        room_id: this.data.room_id,
      },
      success: function (resdata) {
        wx.hideLoading();
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            anchorPopupData: res.data,
            changeAnchor: false,
          });
          if (res.data.is_concern == 1) {
            that.setData({
              focusBol: false,
            });
          } else {
            that.setData({
              focusBol: true,
            });
          }
          that.setData({
            showUser: true,
            shade: true,
          });
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        wx.hideLoading();
        console.log(res.msg);
      },
    });
  },
  //预先下载图片数据
  downImg() {
    let that = this;
    if (this.data.postData.avatar) {
      wx.downloadFile({
        url: this.data.postData.avatar, // 服务器返回的图片地址
        success: (res) => {
          that.setData({
            "postData.avatar": res.tempFilePath,
          });
          if (that.data.postData.cover) {
            wx.downloadFile({
              url: that.data.postData.cover, // 服务器返回的图片地址
              success: (res) => {
                that.setData({
                  "postData.cover": res.tempFilePath,
                });
                // 获取图片信息
                wx.getImageInfo({
                  src: that.data.postData.cover,
                  success(res) {
                    that.setData({
                      "postData.imgData": res,
                    });
                    if (that.data.postData.m_avatar) {
                      wx.downloadFile({
                        url: that.data.postData.m_avatar, // 服务器返回的图片地址
                        success: (res) => {
                          that.setData({
                            "postData.m_avatar": res.tempFilePath,
                          });
                          if (that.data.postData.qr_code) {
                            wx.downloadFile({
                              url: that.data.postData.qr_code, // 服务器返回的图片地址
                              success: (res) => {
                                that.setData({
                                  "postData.qr_code": res.tempFilePath,
                                });
                                if (that.data.postData.shop_logo) {
                                  wx.downloadFile({
                                    url: that.data.postData.shop_logo, // 服务器返回的图片地址
                                    success: (res) => {
                                      that.setData({
                                        "postData.shop_logo": res.tempFilePath,
                                      });
                                      if(that.data.roomData.is_share_word != 1){
                                        //没有开启自定义分享语设置
                                        that.getAvaterInfo();
                                      }
                                    },
                                    fail: function (res) {
                                      that.setData({
                                        loadingMessage:
                                          "海报生成失败，商城图标下载失败",
                                      });
                                      // 失败回调
                                      console.log(res, "失败");
                                    },
                                  });
                                } else {
                                  that.setData({
                                    "postData.shop_logo": "",
                                  });
                                  if(that.data.roomData.is_share_word != 1){
                                    //没有开启自定义分享语设置
                                    that.getAvaterInfo();
                                  }
                                }
                              },
                              fail: function (res) {
                                // 失败回调
                                console.log(res, "失败");
                                that.setData({
                                  loadingMessage:
                                    "海报生成失败，小程序二维码下载失败",
                                });
                              },
                            });
                          }
                        },
                        fail: function (res) {
                          // 失败回调
                          that.setData({
                            loadingMessage:
                              "海报生成失败，用户头像图片下载失败",
                          });
                          console.log(res, "失败");
                        },
                      });
                    }
                  },
                });
                // res.tempFilePath是网络图片的本地地址
              },
              fail: function (res) {
                // 失败回调
                that.setData({
                  loadingMessage: "海报生成失败，直播封面图片下载失败",
                });
                console.log(res, "失败");
              },
            });
          }
          // res.tempFilePath是网络图片的本地地址
        },
        fail: function (res) {
          that.setData({
            loadingMessage: "海报生成失败，主播头像图片下载失败",
          });
          // 失败回调
          console.log(res, "失败");
        },
      });
    }
  },
  //获取海报
  getPoster() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.room.frontend.live-list.room-post");
    let json = {};
    if (that.data.room_id) {
      json.id = this.data.room_id;
    }
    if (that.data.playerType) {
      json.playerType = this.data.playerType;
    }
    if (that.data.backid) {
      json.backid = this.data.backid;
    }
    if (that.data.memberid) {
      json.memberid = this.data.memberid;
    }
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: json,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            postData: res.data,
          });
          that.downImg(); //预先加载画布所需图片
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res.msg);
      },
    });
  },
  smallWindowClose1(){
    this.data.smallWindowIn = true;
    // console.log(this.data.rewardTimeOut,'进入小窗onhide的时候不清除定时器smallWindowClosesmallWindowClosesmallWindowClosesmallWindowClose')
  },
  smallWindowClose(){
    // 播放器退出小窗
    this.data.smallWindowIn = false;
    // console.log(this.data.rewardTimeOut,'退出小窗，smallWindowClosesmallWindowClosesmallWindowClosesmallWindowClose')
  },
  statechange(e) {
    let code = e.detail.code;
    // console.log("llll:::", code,'rewardTimeOut',this.data.rewardTimeOut,'code_id',this.data.code_id);
    // 观看奖励 一分钟后请求接口
    if(code == "2004" && this.data.code_id){
      if(!this.data.rewardTimeOut){
        // console.log('llll:::直播请求定时器')
        this.data.rewardTimeOut = setInterval(() => {
          this.rewardLive();
        }, 60000);
      }
    }
    if(code == "2006" && this.data.code_id){
      // 直播结束，但是如果在pk，则不取消定时器
      if(!this.data.isLivePK){
        this.data.rewardTimeOut = null;
        // console.log('clearInterval')
        clearInterval(this.data.rewardTimeOut);
      }
    }
    if (code == "2002" || code == "2002") {
      wx.hideLoading({});
    }
  },
  // 观看奖励请求
  rewardLive(){
    // var mytime=new Date().toLocaleTimeString(); 
    // wx.showToast({
    //   title: mytime,
    //   icon:'none',
    //   duration:1000
    // })
    let urlStr = app.getNetAddresss("plugin.room.frontend.live.room-view");
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: {
        code_id: this.data.code_id,
        room_id: this.data.room_id,
      },
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          console.log('成功');
        }
      },
      fail: function (res) {
        console.log(res.msg);
      },
    });
  },
  error(e) {
    this.data.rewardTimeOut = null;
    // console.log('clearInterval')
    clearInterval(this.data.rewardTimeOut);
    wx.hideLoading({});
    wx.showModal({
      title: "提示",
      content: "错误提示" + e.detail.errMsg + "(返回直播列表)",
      success(res) {
        if (res.confirm) {
          wx.redirectTo({
            url: "/packageD/directSeeding/liveList/liveList",
          });
        }
      },
    });
    console.log("kkkk:::", e);
  },
  statechangePK(e){
    let code = e.detail.code;
    // console.log("拉取连麦:::", code,'rewardTimeOut',this.data.rewardTimeOut,'code_id',this.data.code_id);
    if(code == "2004" && this.data.code_id){
      if(!this.data.rewardTimeOut){
        this.data.rewardTimeOut = setInterval(() => {
          this.rewardLive();
        }, 60000);
      }
    }

    if (code == "2002" || code == "2002") {
      wx.hideLoading({});
    }
  },
  errorPK(e) {
    this.data.rewardTimeOut = null;
    // console.log('clearInterval')
    clearInterval(this.data.rewardTimeOut);
    wx.hideLoading({});
    wx.showToast({
      title: '拉取连麦失败',
      icon: 'success',
      duration: 2000
    });
    console.log("拉取连麦失败:::", e);
  },
  //退出群组
  quitGroup() {
    let that = this;
    if (that.data.lastGroupId) {
      let promise = that.data.tim.quitGroup(that.data.lastGroupId);
      promise
        .then(function (imResponse) {
          console.log(imResponse.data.groupID); // 退出成功的群 ID
        })
        .catch(function (imError) {
          console.warn("quitGroup error:", imError); // 退出群组失败的相关信息
        });
    }
    clearTimeout(this.data.giftEffectsTime);
  },
  //获取群详细资料
  chatJoinGroup() {
    let that = this;
    that.data.lastGroupId = that.data.roomData.groupId;
    let promise = that.data.tim.joinGroup({
      groupID: that.data.roomData.groupId,
      type: TIM.TYPES.GRP_CHATROOM,
    });
    promise
      .then(function (imResponse) {
        switch (imResponse.data.status) {
        case TIM.TYPES.JOIN_STATUS_WAIT_APPROVAL:
          break; // 等待管理员同意
        case TIM.TYPES.JOIN_STATUS_SUCCESS: // 加群成功
          console.log(imResponse.data.group); // 加入的群组资料
          break;
        default:
          break;
        }
        that.comeRoom();
        that.data.imReadly = false;
      })
      .catch(function (imError) {
        that.comeRoom();
        that.data.imReadly = false;
        console.warn("joinGroup error:", imError); // 申请加群失败的相关信息
      });
  },
  //查询我的个人信息
  chatMyProfile() {
    let that = this;
    let promise = that.data.tim.getMyProfile();
    promise
      .then(function (imResponse) {
        console.log(imResponse.data); // 个人资料 - Profile 实例
        let myData = imResponse.data;
        if (!myData.nick) {
          that.changeMyProfile();
        }
      })
      .catch(function (imError) {
        console.warn("getMyProfile error:", imError); // 获取个人资料失败的相关信息
      });
  },
  //修改我的个人信息
  changeMyProfile() {
    let that = this;
    let promise = that.data.tim.updateMyProfile({
      nick: that.data.roomData.userNickname,
      avatar: that.data.roomData.userAvatar,
    });
    promise
      .then(function (imResponse) {
        console.log(imResponse.data); // 更新资料成功
      })
      .catch(function (imError) {
        console.warn("updateMyProfile error:", imError); // 更新资料失败的相关信息
      });
  },
  //领取营销活动
  activityDataBtn(e) {
    if (this.data.activityDataBtnBol) {
      return false;
    }
    this.data.activityDataBtnBol = true;
    let id = e.currentTarget.dataset.id;
    let index = e.currentTarget.dataset.index;
    if (this.data.activityDataArray[index].activityData.status == 2) {
      return false;
    }
    let that = this;
    let urlStr = app.getNetAddresss(
      "plugin.room.frontend.live.member-activity"
    );
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: {
        room_id: this.data.room_id,
        activity_id: id,
      },
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
          let activitymessage = res.data;
          if (activitymessage.balanceBonus == 1) {
            that.setData({
              ["activityDataArray[" +
              index +
              "].activityData.balanceBonusStatus"]: 2,
            });
          } else {
            that.setData({
              ["activityDataArray[" +
              index +
              "].activityData.balanceBonusStatus"]: 3,
            });
          }
          let activityList =
            that.data.activityDataArray[index].activityData.activityList;
          if (activitymessage.coupon == 1) {
            activityList.forEach((val, idx) => {
              activityList[idx].status = 2;
            });
            that.setData({
              ["activityDataArray[" +
              index +
              "].activityData.activityList"]: activityList,
            });
          } else {
            activityList.forEach((val, idx) => {
              activityList[idx].status = 3;
            });
            that.setData({
              ["activityDataArray[" +
              index +
              "].activityData.activityList"]: activityList,
            });
          }
          if (activitymessage.loveBonus == 1) {
            that.setData({
              ["activityDataArray[" +
              index +
              "].activityData.loveBonusStatus"]: 2,
            });
          } else {
            that.setData({
              ["activityDataArray[" +
              index +
              "].activityData.loveBonusStatus"]: 3,
            });
          }

          if (activitymessage.packetBonus == 1) {
            that.setData({
              ["activityDataArray[" +
              index +
              "].activityData.packetBonusStatus"]: 2,
            });
          } else {
            that.setData({
              ["activityDataArray[" +
              index +
              "].activityData.packetBonusStatus"]: 3,
            });
          }

          if (activitymessage.pointBonus == 1) {
            that.setData({
              ["activityDataArray[" +
              index +
              "].activityData.pointBonusStatus"]: 2,
            });
          } else {
            that.setData({
              ["activityDataArray[" +
              index +
              "].activityData.pointBonusStatus"]: 3,
            });
          }
          that.setData({
            ["activityDataArray[" + index + "].activityData.status"]: 2,
          });
          that.data.activityDataBtnBol = false;
        } else {
          that.data.activityDataBtnBol = false;
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res.msg);
      },
    });
  },
  //聊天事件
  chatEventList() {
    let that = this;
    // 监听事件，例如：
    that.data.tim.on(TIM.EVENT.SDK_READY, function (event) {
      // 收到离线消息和会话列表同步完毕通知，接入侧可以调用 sendMessage 等需要鉴权的接口
      that.data.sendMessageReadly = false;
      that.chatMyProfile();
      // that.chatJoinGroup()
      // event.name - TIM.EVENT.SDK_READY
    });
    that.data.tim.on(TIM.EVENT.MESSAGE_RECEIVED, function (event) {
      //防止重新接受两条信息
      if (
        event.data[0].type == "TIMCustomElem" &&
        event.data[0].payload &&
        event.data[0].payload.extension == "customText"
      ) {
        if (that.data.lasttime == event.data[0].time) {
          return;
        } else {
          that.data.lasttime = event.data[0].time;
        }
      }
      let message = event.data;
      let tipsContent = that.data.tipsContent;
      let giftListContent = that.data.giftListContent;
      let roomMemberContent = that.data.roomMemberContent;
      message.forEach(function (val, index) {
        let conversationType = val.conversationType;
        
        //判断消息来源群或者个人
        if (conversationType == TIM.TYPES.CONV_GROUP) {
          let data = val;
          //后台发送过来的消息处理
          if (data.from == "administrator") {
            if (data.payload.extension == "end") {
              wx.showModal({
                title: "提示",
                content: "直播已经结束",
                showCancel: false,
                success(res) {
                  if (res.confirm) {
                    wx.redirectTo({
                      url: "/packageD/directSeeding/liveList/liveList",
                    });
                  }
                },
              });
            } else if (data.payload.extension == "explain_goods") {
              if (data.payload.description) {
                let json = JSON.parse(data.payload.description);
                that.setData({
                  explainingGoods: json,
                });
              }
            } else if (data.payload.extension == "cancel_explain") {
              that.setData({
                "explainingGoods.goods_id": "",
              });
            } else if (data.payload.extension == "chat_reply") {
              if (data.payload.description) {
                let json = JSON.parse(data.payload.description);
                let member_id = json.member_id;
                if (that.data.roomData.userID == member_id) {
                  wx.showModal({
                    title: "提示",
                    content: "您已经解除禁言",
                    showCancel: false,
                    success(res) {},
                  });
                  that.setData({
                    room_ban: false,
                  });
                }
              }
            } else if (data.payload.extension == "chat_ban") {
              if (data.payload.description) {
                let json = JSON.parse(data.payload.description);
                let member_id = json.member_id;
                if (that.data.roomData.userID == member_id) {
                  wx.showModal({
                    title: "提示",
                    content: "您已经被禁言",
                    showCancel: false,
                    success(res) {},
                  });
                  that.setData({
                    room_ban: true,
                  });
                }
              }
            } else if (data.payload.extension == "room_ban") {
              if (data.payload.description) {
                let json = JSON.parse(data.payload.description);
                let member_id = json.member_id;
                if (that.data.roomData.userID == member_id) {
                  that.setData({
                    picturemodeshow: false,
                  });
                  wx.showModal({
                    title: "提示",
                    content: "您已被禁入直播间",
                    showCancel: false,
                    success(res) {
                      if (res.confirm) {
                        wx.redirectTo({
                          url: "/packageD/directSeeding/liveList/liveList",
                        });
                      }
                    },
                  });
                }
              }
            } else if (data.payload.extension == "ban") {
              wx.showModal({
                title: "提示",
                content: "直播已经封禁",
                showCancel: false,
                success(res) {
                  if (res.confirm) {
                    wx.redirectTo({
                      url: "/packageD/directSeeding/liveList/liveList",
                    });
                  }
                },
              });
            } else if (data.payload.extension == "welcome") {
              // if (data.payload.description) {
              // 	let json = JSON.parse(data.payload.description);
              // 	let messageList = that.data.messageList;
              // 	messageList.push({
              // 		content: json.content
              // 	})
              // 	that.setData({
              // 		messageList,
              // 		messagesTop: messageList.length * 1000
              // 	})
              // }
            } else if (data.payload.extension == "leave") {
              wx.showModal({
                title: "提示",
                content: "主播暂时离开",
                showCancel: false,
                success(res) {},
              });
            } else if (data.payload.extension == "online") {
              wx.showModal({
                title: "提示",
                content: "主播重新连接",
                showCancel: false,
                success(res) {
                  if (res.confirm) {
                    that.data.roomObj.play({
                      success() {
                        wx.showToast({
                          icon: "none",
                          title: "正在重新启动播放",
                          duration: 1500,
                        });
                      },
                      fail() {
                        wx.showToast({
                          icon: "none",
                          title: "重新启动播放失败",
                          duration: 1500,
                        });
                      },
                    });
                  }
                },
              });
            } else if (data.payload.extension == "reward") {
              //打赏
              if (data.payload.description) {
                let json = JSON.parse(data.payload.description);
                if (json.show_effect == 1) {
                  //开启特效
                  let specialList = that.data.specialList;
                  specialList.push({
                    nickname: json.nickname,
                    reward_name: "送主播" + json.reward_name,
                    img: json.avatar,
                    effect_time: json.effect_time,
                    effect_type: json.effect_type,
                    effect_gif: `${json.effect_gif}?v=${Date.now()}` //防止gif第二次取缓存不播放
                  });
                  that.setData({specialList});
                  if (that.data.specialList.length <= 1) that.giftEffectsTimer();
                } else {
                  giftListContent.push({
                    nickname: json.nickname,
                    avatar: json.avatar,
                    reward_name: "送主播" + json.reward_name,
                    reward_icon: json.reward_icon,
                  });
                  that.data.giftListContent = giftListContent;
                }
              }
            } else if (data.payload.extension == "virtual_view_num") {
              //观看人数
              if (data.payload.description) {
                let json = JSON.parse(data.payload.description);
                console.log(json);
                that.setData({
                  view_num: json.view_num,
                });
              }
            } else if (data.payload.extension == "concern") {
              //关注
              if (data.payload.description) {
                let json = JSON.parse(data.payload.description);
                tipsContent.push({
                  type: "concern",
                  nickname: json.nickname,
                });
                that.data.tipsContent = tipsContent;
              }
            } else if (data.payload.extension == "buy") {
              //正在买
              if (data.payload.description) {
                let json = JSON.parse(data.payload.description);
                tipsContent.push({
                  type: "buy",
                  nickname: json.nickname,
                  count: json.count,
                });
                that.data.tipsContent = tipsContent;
              }
            } else if (data.payload.extension == "come") {
              //进入直播间
              // if (data.payload.description) {
              // 	let json = JSON.parse(data.payload.description);
              // 	tipsContent.push({
              // 		type: "come",
              // 		nickname: json.nickname
              // 	})
              // 	that.data.tipsContent = tipsContent;
              // }
            } else if (data.payload.extension == "room_member") {
              //进入活动
              if (data.payload.description) {
                let json = JSON.parse(data.payload.description);
                roomMemberContent.push(json);
                that.data.roomMemberContent = roomMemberContent;
              }
              that.getroomMember(that.data.roomMemberContent.length - 1);
            }  else if (data.type == "TIMCustomElem") {
              if (data.payload.extension == "open_chat") {
                //开启评论
                that.setData({
                  close_chat: 0
                });
              } else if (data.payload.extension == "close_chat") {
                //开启评论
                that.setData({
                  close_chat: 1
                });
              } else if (data.payload.extension == "open_reward") {
                //开启评论
                that.setData({
                  close_reward: 0
                });
              } else if (data.payload.extension == "close_reward") {
                //开启评论
                that.setData({
                  close_reward: 1
                });
              }
            }
          } else if (data.type == "TIMTextElem") {
            // let messageList = that.data.messageList;
            // messageList.push({
            // 	nick: data.nick,
            // 	id: data.from,
            // 	text: data.payload.text
            // })
            // that.setData({
            // 	messageList,
            // 	messagesTop: messageList.length * 1000
            // })
          } else if (data.type == "TIMCustomElem") {
            //自定义类型解析
            console.log("有信息了======",JSON.parse(data.payload.description));
            if(data.payload.extension == "customPkGroup"){
              that.data.startPKTime = Date.parse(new Date()) / 1000;
              that.data.pkTimer = setInterval(function() {
                that.GetRTime();
              }, 1000);
              that.setData({
                livePKData: JSON.parse(data.payload.description),
                livePKSrc: that.data.roomData.play_url_rtmp.match(/(\S*)\/live\//)[1]+'/live/' + JSON.parse(data.payload.description).streamid,
                isLivePK: true,
              });
            } else if (data.payload.extension == "customQuitPkGroup") {
              // 结束连麦
              that.setData({
                livePKData: {},
                livePKSrc: "",
                isLivePK: false,
                PKTimed: "00:00:00"
              });
              // console.log('clearInterval')
              clearInterval(that.data.pkTimer);
            } else if (data.payload.extension == "customText") {
              let messageList = that.data.messageList;
              let messageListData = JSON.parse(data.payload.description);
              if (messageListData && messageListData.memberLevelName) {
                messageListData.memberLevelName = messageListData.memberLevelName.substr(
                  0,
                  2
                );
              }
              messageList.push(messageListData);
              that.setData({
                messageList,
                messagesTop: messageList.length * 1000,
              });
            } else if (data.payload.extension == "come") {
              //进入直播间
              if (data.payload.description) {
                let json = JSON.parse(data.payload.description);
                tipsContent.push({
                  type: "come",
                  nickname: json.nickname,
                });
                that.data.tipsContent = tipsContent;
              }
            } else if (data.payload.extension == "welcome") {
              if (data.payload.description) {
                let json = JSON.parse(data.payload.description);
                let messageList = that.data.messageList;
                messageList.push({
                  content: json.content,
                });
                that.setData({
                  messageList,
                  messagesTop: messageList.length * 1000,
                });
              }
            }
          }
        }
        // else if (conversationType == TIM.TYPES.CONV_C2C) {
        // }
      });
      // 收到推送的单聊、群聊、群提示、群系统通知的新消息，可通过遍历 event.data 获取消息列表数据并渲染到页面
      // event.name - TIM.EVENT.MESSAGE_RECEIVED
      // event.data - 存储 Message 对象的数组 - [Message]
    });

    that.data.tim.on(TIM.EVENT.MESSAGE_REVOKED, function (event) {
      // 收到消息被撤回的通知
      // event.name - TIM.EVENT.MESSAGE_REVOKED
      // event.data - 存储 Message 对象的数组 - [Message] - 每个 Message 对象的 isRevoked 属性值为 true
    });

    that.data.tim.on(TIM.EVENT.CONVERSATION_LIST_UPDATED, function (event) {
      // 收到会话列表更新通知，可通过遍历 event.data 获取会话列表数据并渲染到页面
      // event.name - TIM.EVENT.CONVERSATION_LIST_UPDATED
      // event.data - 存储 Conversation 对象的数组 - [Conversation]
    });

    that.data.tim.on(TIM.EVENT.GROUP_LIST_UPDATED, function (event) {
      // 收到群组列表更新通知，可通过遍历 event.data 获取群组列表数据并渲染到页面
      // event.name - TIM.EVENT.GROUP_LIST_UPDATED
      // event.data - 存储 Group 对象的数组 - [Group]
    });

    that.data.tim.on(TIM.EVENT.GROUP_SYSTEM_NOTICE_RECEIVED, function (event) {
      // 收到新的群系统通知
      // event.name - TIM.EVENT.GROUP_SYSTEM_NOTICE_RECEIVED
      // event.data.type - 群系统通知的类型，详情请参见 GroupSystemNoticePayload 的 operationType 枚举值说明
      // event.data.message - Message 对象，可将 event.data.message.content 渲染到到页面
    });

    that.data.tim.on(TIM.EVENT.PROFILE_UPDATED, function (event) {
      // 收到自己或好友的资料变更通知
      // event.name - TIM.EVENT.PROFILE_UPDATED
      // event.data - 存储 Profile 对象的数组 - [Profile]
    });

    that.data.tim.on(TIM.EVENT.BLACKLIST_UPDATED, function (event) {
      // 收到黑名单列表更新通知
      // event.name - TIM.EVENT.BLACKLIST_UPDATED
      // event.data - 存储 userID 的数组 - [userID]
    });

    that.data.tim.on(TIM.EVENT.ERROR, function (event) {
      // 收到 SDK 发生错误通知，可以获取错误码和错误信息
      // event.name - TIM.EVENT.ERROR
      // event.data.code - 错误码
      // event.data.message - 错误信息
    });

    that.data.tim.on(TIM.EVENT.SDK_NOT_READY, function (event) {
      // 收到 SDK 进入 not ready 状态通知，此时 SDK 无法正常工作
      // event.name - TIM.EVENT.SDK_NOT_READY
    });

    that.data.tim.on(TIM.EVENT.KICKED_OUT, function (event) {
      // 收到被踢下线通知
      // event.name - TIM.EVENT.KICKED_OUT
      // event.data.type - 被踢下线的原因，例如:
      //    - TIM.TYPES.KICKED_OUT_MULT_ACCOUNT 多实例登录被踢
      //    - TIM.TYPES.KICKED_OUT_MULT_DEVICE 多终端登录被踢
      //    - TIM.TYPES.KICKED_OUT_USERSIG_EXPIRED 签名过期被踢
      wx.showToast({
        icon: "none",
        title: "您的IM被踢下线了",
        duration: 2000,
      });
    });
  },
  //im的营销活动提交
  roomMemberBtn(e) {
    if (this.data.roomMemberBtnBol) {
      return false;
    }
    this.data.roomMemberBtnBol = true;
    let id = e.currentTarget.dataset.id;
    let index = e.currentTarget.dataset.index;
    if (this.data.roomMemberContentArray[index].activityData.status == 2) {
      return false;
    }
    let that = this;
    let urlStr = app.getNetAddresss(
      "plugin.room.frontend.live.room-member-activity"
    );
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: {
        room_id: this.data.room_id,
        activity_id: id,
      },
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
          let activitymessage = res.data;
          if (activitymessage.balanceBonus == 1) {
            that.setData({
              ["roomMemberContentArray[" +
              index +
              "].activityData.balanceBonusStatus"]: 2,
            });
          } else {
            that.setData({
              ["roomMemberContentArray[" +
              index +
              "].activityData.balanceBonusStatus"]: 3,
            });
          }
          let activityList =
            that.data.roomMemberContentArray[index].activityData.activityList;
          if (activitymessage.coupon == 1) {
            activityList.forEach((val, idx) => {
              activityList[idx].status = 2;
            });
            that.setData({
              ["roomMemberContentArray[" +
              index +
              "].activityData.activityList"]: activityList,
            });
          } else {
            activityList.forEach((val, idx) => {
              activityList[idx].status = 3;
            });
            that.setData({
              ["roomMemberContentArray[" +
              index +
              "].activityData.activityList"]: activityList,
            });
          }
          if (activitymessage.loveBonus == 1) {
            that.setData({
              ["roomMemberContentArray[" +
              index +
              "].activityData.loveBonusStatus"]: 2,
            });
          } else {
            that.setData({
              ["roomMemberContentArray[" +
              index +
              "].activityData.loveBonusStatus"]: 3,
            });
          }

          if (activitymessage.packetBonus == 1) {
            that.setData({
              ["roomMemberContentArray[" +
              index +
              "].activityData.packetBonusStatus"]: 2,
            });
          } else {
            that.setData({
              ["roomMemberContentArray[" +
              index +
              "].activityData.packetBonusStatus"]: 3,
            });
          }

          if (activitymessage.pointBonus == 1) {
            that.setData({
              ["roomMemberContentArray[" +
              index +
              "].activityData.pointBonusStatus"]: 2,
            });
          } else {
            that.setData({
              ["roomMemberContentArray[" +
              index +
              "].activityData.pointBonusStatus"]: 3,
            });
          }
          that.setData({
            ["roomMemberContentArray[" + index + "].activityData.status"]: 2,
          });
          that.data.roomMemberBtnBol = false;
        } else {
          that.data.roomMemberBtnBol = false;
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res.msg);
      },
    });
  },
  //im的营销活动
  getroomMember(first_index) {
    let that = this;
    let roomMemberContent = that.data.roomMemberContent[first_index];
    let roomMemberContentArray = that.data.roomMemberContentArray;
    // let roomMemberTimeArray = that.data.roomMemberTimeArray;
    if (roomMemberContent) {
      let activity = roomMemberContent;
      let activityList = [];
      // let startTime = 0;
      if (activity.coupon && activity.coupon.coupon_id) {
        activity.coupon.coupon_id.forEach((val, index) => {
          activityList.push({
            coupon_id: activity.coupon.coupon_id[index],
            coupon_name: activity.coupon.coupon_name[index],
            coupon_several: activity.coupon.coupon_several[index],
            status: 1,
          });
        });
      }
      // if (activity.liveTime) {
      //   startTime = activity.liveTime * 60 * 1000;
      // }
      activity.activityList = activityList;
      activity.pointBonusStatus = 1;
      activity.loveBonusStatus = 1;
      activity.balanceBonusStatus = 1;
      activity.packetBonusStatus = 1;
      activity.status = 1;
      activity.showactivity = false;
      roomMemberContentArray.push({
        activityData: activity,
      });
      // if (startTime) {
      // 	let activityTime = null;
      // 	activityTime = setTimeout(function() {
      // 		that.setData({
      // 			['roomMemberContentArray[' + first_index + '].activityData.showactivity']: true
      // 		})
      // 	}, startTime)
      // 	roomMemberTimeArray.push(activityTime)
      // }
      that.setData({
        roomMemberContentArray: roomMemberContentArray,
        // roomMemberTimeArray: roomMemberTimeArray
      });
      that.setData({
        ["roomMemberContentArray[" +
        first_index +
        "].activityData.showactivity"]: true,
      });
    }
  },
  logout() {
    let that = this;
    let promise = that.data.tim.logout();
    promise
      .then(function (imResponse) {
        console.log(imResponse.data); // 登出成功
      })
      .catch(function (imError) {
        console.warn("logout error:", imError);
      });
  },
  //聊天登录
  chatLogin() {
    let that = this;
    let promise = that.data.tim.login({
      userID: that.data.roomData.userID.toString(),
      userSig: that.data.roomData.userSig,
    });
    promise
      .then(function (imResponse) {
        console.log(imResponse.data); // 登录成功
        that.chatJoinGroup();
      })
      .catch(function (imError) {
        console.warn("login error:", imError); // 登录失败的相关信息
      });
  },
  getGiftList() {
    wx.showLoading({
      title: "加载中",
    });
    let that = this;
    let urlStr = app.getNetAddresss("plugin.room.frontend.live.reward-list");
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: {},
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            giftListData: res.data.list,
            giftMemberData: res.data.member,
            giftType: res.data.type ? res.data.type : {},
            showGift: true,
            shade: true,
          });
          // let giftMemberData = that.data.giftMemberData;
          let giftType = that.data.giftType;
          if (giftType && giftType.integral == 1) {
            that.setData({
              activeNum: 1,
            });
          } else if (giftType && giftType.balance == 1) {
            that.setData({
              activeNum: 2,
            });
          } else if (giftType && giftType.love == 1) {
            that.setData({
              activeNum: 3,
            });
          }
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
        wx.hideLoading();
      },
      fail: function (res) {
        wx.hideLoading();
        console.log(res.msg);
      },
    });
  },
  getData(index) {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.room.frontend.live.room");
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: {
        id: this.data.room_id,
        password: this.data.passwordVal,
      },
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          if (res.data.purview == 2) {
            wx.hideToast({});
            wx.showModal({
              title: "提示",
              content: "密码错误,是否重新输入密码?",
              success(res) {
                if (res.confirm) {
                  if (index !== undefined) {
                    that.setData({
                      passwordIndex: index,
                    });
                  }
                  that.setData({
                    passwordShow: true,
                  });
                } else if (res.cancel) {
                  wx.redirectTo({
                    url: "/packageD/directSeeding/liveList/liveList",
                  });
                }
              },
            });
            return;
          } else if (res.data.purview == 3) {
            wx.hideToast({});
            wx.showModal({
              title: "提示",
              content: "需要密码访问,是否输入密码?",
              success(res) {
                if (res.confirm) {
                  if (index !== undefined) {
                    that.setData({
                      passwordIndex: index,
                    });
                  }
                  that.setData({
                    passwordShow: true,
                  });
                } else if (res.cancel) {
                  wx.redirectTo({
                    url: "/packageD/directSeeding/liveList/liveList",
                  });
                }
              },
            });
            return;
          } else if (res.data.purview == 4) {
            wx.hideToast({});
            wx.showModal({
              title: "提示",
              content: "没有访问权限",
              showCancel: false,
              success(res) {
                if (res.confirm) {
                  wx.redirectTo({
                    url: "/packageD/directSeeding/liveList/liveList",
                  });
                }
              },
            });
            that.setData({
              passwordShow: false,
            });
            return;
          } else {
            that.setData({
              passwordShow: false,
            });
          }
          if (res.data.status == 4) {
            wx.hideToast({});
            wx.showModal({
              title: "提示",
              content: "直播已经结束",
              showCancel: false,
              success(res_1) {
                if (res_1.confirm) {
                  if (res.data && res.data.back_id) {
                    wx.navigateTo({
                      url:
                        "/packageD/directSeeding/livePage/livePage?id=" +
                        that.data.room_id +
                        "&playerType=video" +
                        "&backid=" +
                        res.data.back_id,
                    });
                  } else {
                    wx.redirectTo({
                      url: "/packageD/directSeeding/liveList/liveList",
                    });
                  }
                }
              },
            });
            return;
          } else if (res.data.status == 1) {
            wx.hideToast({});
            wx.showModal({
              title: "提示",
              content: "直播等待审核中，请稍后再来",
              showCancel: false,
              success(res) {
                if (res.confirm) {
                  wx.redirectTo({
                    url: "/packageD/directSeeding/liveList/liveList",
                  });
                }
              },
            });
            return;
          } else if (res.data.status == 2) {
            wx.hideToast({});
            wx.showModal({
              title: "提示",
              content: "等待直播中，请稍后再来",
              showCancel: false,
              success(res) {
                if (res.confirm) {
                  if(this.data.code_id){
                    wx.redirectTo({
                      url: "/packageD/directSeeding/liveList/liveList?cd="+this.data.code_id,
                    });
                  }else{
                    wx.redirectTo({
                      url: "/packageD/directSeeding/liveList/liveList",
                    });
                  }
                  
                }
              },
            });
            return;
          }
          if (res.data.online_status && res.data.online_status == "forbid") {
            wx.hideToast({});
            wx.showModal({
              title: "提示",
              content: "抱歉,该直播间被禁用了",
              showCancel: false,
              success(res) {
                if (res.confirm) {
                  wx.redirectTo({
                    url: "/packageD/directSeeding/liveList/liveList",
                  });
                }
              },
            });
            return;
          } else if (
            res.data.online_status &&
            res.data.online_status == "inactive"
          ) {
            wx.hideToast({});
            wx.showModal({
              title: "提示",
              content: "抱歉,该主播暂时离开",
              showCancel: false,
              success(res) {},
            });
          }
          that.setData({
            shownum: res.data.like_num ? res.data.like_num : 0,
            roomData: res.data,
            id: res.data.member_id,
            view_num: res.data.view_num,
            roomMemberContentArray: [],
            roomMemberContent: [],
            IMmessage: res.data.message,
            luck_number: res.data.luck_number || 0,
            close_reward: res.data.close_reward || 0,
            close_chat: res.data.close_chat || 0,
            mode_button: res.data.mode_button || 0
          });
          if (that.data.last_room_id == that.data.room_id) {
            that.setData({
              "liveListData[0].avatar": res.data.avatar,
              "liveListData[0].cover": res.data.cover,
              "liveListData[0].banner": res.data.banner,
            });
          }

          if (res.data.voice_status) {
            that.setData({
              livePKData: res.data.voice_anchor,
              livePKSrc: res.data.voice_anchor.play_url.play_url_rtmp,
              isLivePK: true
            });
            that.data.startPKTime = res.data.voice_anchor.start_time||Date.parse(new Date()) / 1000;
            that.data.pkTimer = setInterval(function() {
              that.GetRTime();
            }, 1000);
          }

          if (res.data.is_concern == 1) {
            that.setData({
              focusBol: false,
            });
          } else {
            that.setData({
              focusBol: true,
            });
          }
          that.activeRoomSet();
          if (res.data.IM == 1) {
            setTimeout(() => {
              that.chatLogin();
            }, 1000);
          }
          // for (let k = 0; k < that.data.roomMemberTimeArray.length; k++) {
          // 	clearTimeout(that.data.roomMemberTimeArray[k]);
          // }
          // that.data.roomMemberTimeArray = []
          if (index !== undefined) {
            that.setData({
              ["liveListData[" + index + "].changeloadBol"]: true,
            });
          }
          for (let j = 0; j < that.data.activityTimeArray.length; j++) {
            clearTimeout(that.data.activityTimeArray[j]);
          }
          that.data.activityTimeArray = [];
          if (res.data.view_activity == 1) {
            let activityArray = res.data.activity;
            let activityDataArray = [];
            let activityTimeArray = that.data.activityTimeArray;
            for (let i = 0; i < activityArray.length; i++) {
              let activity = activityArray[i];
              let activityList = activity.coupon;
              let startTime = 0;
              // if (activity.coupon && activity.coupon.coupon_id) {
              //   activity.coupon.coupon_id.forEach((val, index) => {
              //     activityList.push({
              //       coupon_id: activity.coupon.coupon_id[index],
              //       coupon_name: activity.coupon.coupon_name[index],
              //       coupon_several: activity.coupon.coupon_several[index],
              //       status: 1,
              //     });
              //   });
              // }
              if (activity.liveTime) {
                startTime = activity.liveTime * 60 * 1000;
              }
              activity.activityList = activityList;
              activity.pointBonusStatus = 1;
              activity.loveBonusStatus = 1;
              activity.balanceBonusStatus = 1;
              activity.packetBonusStatus = 1;
              activity.status = 1;
              activity.showactivity = false;
              activityDataArray.push({
                activityData: activity,
              });
              if (startTime) {
                let activityTime = null;
                activityTime = setTimeout(function () {
                  that.setData({
                    ["activityDataArray[" +
                    i +
                    "].activityData.showactivity"]: true,
                  });
                }, startTime);
                activityTimeArray.push(activityTime);
              }
            }
            that.setData({
              activityTimeArray: activityTimeArray,
              activityDataArray: activityDataArray,
            });
          }
          // that.data.tipsContent = [];
          // that.data.giftListContent = [];
          // that.setData({
          // 	tipsContentMsssage: "",
          // 	giftListmessage: {}
          // })
          clearTimeout(timer_1);
          clearTimeout(timer_2);
          clearTimeout(timer_3);
          that.getGiftEffect(); //开启礼物效果
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res.msg);
      },
    });
  },
  passwordLiveBtn() {
    if (this.data.passwordIndex !== undefined) {
      this.getData(this.data.passwordIndex);
    } else {
      this.getData(0);
    }
  },
  //查看优惠券
  goCoupon() {
    wx.navigateTo({
      url: "/packageA/member/coupon_v2/coupon_v2",
    });
  },
  //跳转积分
  goIntegral() {
    wx.navigateTo({
      url: "/packageB/member/integral/integral",
    });
  },
  //查看爱心值
  goLoveindex() {
    wx.navigateTo({
      url: "/packageB/member/love/Love_index/Love_index",
    });
  },
  //查看余额
  gobalance() {
    wx.navigateTo({
      url: "/packageA/member/balance/balance/balance",
    });
  },
  //是否取消关注
  followBtn() {
    if (this.data.focusBol) {
      this.addConcern();
    } else {
      this.cancelConcern();
    }
  },
  addConcern() {
    //添加关注
    let that = this;
    let urlStr = app.getNetAddresss("plugin.room.frontend.live.concern");
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: {
        member_id: this.data.id,
        room_id: this.data.room_id,
      },
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          wx.showToast({
            icon: "none",
            title: "关注成功!",
            duration: 1500,
          });
          that.setData({
            focusBol: false,
          });
          that.newMedia(2);
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res.msg);
      },
    });
  },
  cancelConcern() {
    //取消关注
    let that = this;
    let urlStr = app.getNetAddresss(
      "plugin.room.frontend.anchor.cancel-concern"
    );
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: {
        member_id: this.data.id,
      },
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          wx.showToast({
            icon: "none",
            title: "取消关注!",
            duration: 1500,
          });
          that.setData({
            focusBol: true,
          });
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res.msg);
      },
    });
  },
  //跳转个人主页
  goHomePage() {
    wx.navigateTo({
      url:
        "/packageD/directSeeding/anchorDetail/anchorDetail?id=" + this.data.id,
    });
  },
  //跳转店铺
  goPage(e) {
    let roleid = e.currentTarget.dataset.roleid;
    let shopid = e.currentTarget.dataset.shopid;
    if (roleid == 1) {
      wx.navigateTo({
        url: "/packageC/o2o/o2oStore/o2oStore?store_id=" + shopid,
      });
    } else if (roleid == 2) {
      wx.navigateTo({
        url: "/packageA/member/supplier/SupplierShop/SupplierShop?id=" + shopid,
      });
    } else if (roleid == 3) {
      wx.navigateTo({
        url: "/packageC/hotel/HotelHome/HotelHome?id=" + shopid,
      });
    } else {
      wx.reLaunch({
        url: "/packageG/index/index",
      });
    }
  },
  //跳转购物车
  goGood(e) {
    let id = e.currentTarget.dataset.id;
    let that = this;
    let urlStr = app.getNetAddresss("plugin.room.frontend.live.check-goods");
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: {
        goods_id: id,
        room_id: that.data.room_id,
      },
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            showGoodLift: false,
            shade: false,
          });
          wx.navigateTo({
            url:
              "/packageA/detail_v2/detail_v2?id=" +
              id +
              "&liveshow=1&roomid=" +
              that.data.room_id,
          });
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res.msg);
      },
    });
  },
  //礼物选择
  giftSelect(e) {
    let id = e.currentTarget.dataset.id;
    let index = e.currentTarget.dataset.index;
    this.setData({
      giftSelectId: id,
    });
    this.data.giftSelectNUm = index;
  },
  //打赏
  rewardBtn() {
    if (!this.data.activeNum) {
      wx.showToast({
        icon: "none",
        title: "请选取礼物支付类型",
        duration: 1500,
      });
    }
    let that = this;
    that.data.usewechatpayBol = false;
    if (this.data.giftSelectBol) {
      return false;
    }
    if (!this.data.giftSelectId) {
      wx.showToast({
        icon: "none",
        title: "请先选取礼物",
        duration: 1500,
      });
      return false;
    } else if (
      this.data.activeNum == 1 &&
      (!this.data.giftMemberData.credit1 ||
        this.data.giftMemberData.credit1 <= 0 ||
        Number(this.data.giftMemberData.credit1) <
          Number(
            this.data.giftListData[this.data.giftSelectNUm].credit1_number
          ))
    ) {
      wx.showToast({
        icon: "none",
        title: this.data.giftMemberData.credit1_name
          ? this.data.giftMemberData.credit1_name + "不足"
          : "积分不足",
        duration: 1500,
      });
      return false;
    } else if (
      this.data.activeNum == 2 &&
      (!this.data.giftMemberData.credit2 ||
        this.data.giftMemberData.credit2 <= 0 ||
        Number(this.data.giftMemberData.credit2) <
          Number(
            this.data.giftListData[this.data.giftSelectNUm].credit2_number
          ))
    ) {
      // wx.showToast({
      // 	icon: 'none',
      // 	title: '余额不足',
      // 	duration: 1500
      // })
      let money = Number(
        this.data.giftListData[this.data.giftSelectNUm].credit2_number
      );
      if (!money || money <= 0) {
        wx.showToast({
          icon: "none",
          title: "打赏的礼物金额价值必须大于零",
          duration: 1500,
        });
        return false;
      }
      that.setData({
        giftmoney: money,
        wechatpayShow: true,
        showGift: false,
        shade: false,
      });
      that.data.giftSelectBol = false;
      return false;
    } else if (
      this.data.activeNum == 3 &&
      (!this.data.giftMemberData.love ||
        this.data.giftMemberData.love <= 0 ||
        Number(this.data.giftMemberData.love) <
          Number(this.data.giftListData[this.data.giftSelectNUm].love_number))
    ) {
      wx.showToast({
        icon: "none",
        title: this.data.giftMemberData.love_name
          ? this.data.giftMemberData.love_name + "不足"
          : "爱心值不足",
        duration: 1500,
      });
      return false;
    }
    this.data.giftSelectBol = true;
    let urlStr = app.getNetAddresss("plugin.room.frontend.reward.index");
    let num = this.data.activeNum;
    let number = 0;
    if (num == 1) {
      number = this.data.giftListData[this.data.giftSelectNUm].credit1_number;
    } else if (num == 2) {
      number = this.data.giftListData[this.data.giftSelectNUm].credit2_number;
    } else if (num == 3) {
      number = this.data.giftListData[this.data.giftSelectNUm].love_number;
    }
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: {
        reward_type: this.data.activeNum,
        room_id: this.data.room_id,
        reward_id: this.data.giftSelectId,
        number: number,
      },
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          wx.showToast({
            icon: "none",
            title: "打赏成功",
            duration: 1500,
          });
          if (num == 1) {
            that.setData({
              "giftMemberData.credit1": Number(
                that.data.giftMemberData.credit1 - number
              ).toFixed(2),
            });
          } else if (num == 2) {
            that.setData({
              "giftMemberData.credit2": Number(
                that.data.giftMemberData.credit2 - number
              ).toFixed(2),
            });
          } else if (num == 3) {
            that.setData({
              "giftMemberData.love": Number(
                that.data.giftMemberData.love - number
              ).toFixed(2),
            });
          }
          that.setData({
            showGift: false,
            shade: false,
          });
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
        that.data.giftSelectBol = false;
      },
      fail: function (res) {
        console.log(res.msg);
      },
    });
  },
  giftListRoll: function () {
    let that = this;
    that.setData({
      giftScreenLeft: -this.data.firstwidth,
    });
    this.giftListRoll_2();
  },
  giftListRoll_2() {
    let that = this;
    timer_1 = setTimeout(() => {
      that.setData({
        giftScreenLeftBol: true,
      });
      that.setData({
        giftScreenLeft: that.data.giftwidth,
      });
      timer_2 = setTimeout(() => {
        that.setData({
          giftScreenLeftBol: false,
        });
        that.setData({
          giftScreenLeft: -that.data.firstwidth,
        });
        if (that.data.giftListContent.length > 0) {
          that.setData({
            giftListmessage: that.data.giftListContent.shift(),
          });
        } else {
          that.setData({
            giftListmessage: {},
          });
        }
        that.giftListRoll_2();
      }, 200);
    }, 6000); // 滚动不需要停顿则将2000改成动画持续时间
  },
  getlikeNum() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.room.frontend.live.likes");
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: {
        room_id: this.data.room_id,
      },
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            shownum: that.data.shownum + 1,
          });
          that.newMedia(1);
        } else {
          // wx.showToast({
          // 	icon: 'none',
          // 	title: res.msg,
          // 	duration: 1500
          // })
        }
      },
      fail: function (res) {
        console.log(res.msg);
      },
    });
  },
  clickHandler: function () {
    if (this.data.likeNumBol) {
      this.getlikeNum();
      this.setData({
        likeNumBol: false,
      });
    }
    // this.setData({
    // 	shownum: this.data.shownum + 1
    // })
    this.likeClick();
  },
  startMove() {
    if (this.data.tipsContent.length > 0) {
      this.data.tipsopacityBol = !this.data.tipsopacityBol;
    }
    setTimeout(() => {
      if (this.data.tipsopacityBol) {
        if (this.data.tipsContent.length > 0) {
          this.setData({
            tipsContentMsssage: this.data.tipsContent.shift(),
          });
          this.setData({
            tipsopacity: 1,
          });
        } else {
          this.setData({
            tipsopacity: 0,
          });
        }
      } else {
        this.setData({
          tipsopacity: 0,
        });
      }
      this.startMove();
    }, 2000); // 滚动不需要停顿则将2000改成动画持续时间
  },
  likeClick() {
    const image = "../../../image/directSeeding/zb_like_icon.png";
    const anmationData = {
      id: new Date().getTime(),
      timer: 0,
      opacity: 0.5,
      pathData: this.generatePathData(),
      image: image,
      factor: {
        speed: 0.006, // 运动速度，值越小越慢
        t: 0, //  贝塞尔函数系数
      },
    };
    if (Object.keys(queue).length > 0) {
      queue[anmationData.id] = anmationData;
    } else {
      queue[anmationData.id] = anmationData;
      this.bubbleAnimate();
    }
  },

  getRandom(min, max) {
    return Math.random() * (max - min) + min;
  },

  getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  },
  /**获取图片路径 */
  generatePathData() {
    let width = this.data.width,
      height = this.data.height;
    const p0 = {
      x: 0.65 * width,
      y: height,
    };
    const p1 = {
      x: this.getRandom(0.22 * width, 0.33 * width),
      y: this.getRandom(0.5 * height, 0.75 * height),
    };
    const p2 = {
      x: this.getRandom(0, 0.88 * width),
      y: this.getRandom(0.25 * height, 0.5 * height),
    };
    const p3 = {
      x: this.getRandom(0, 0.88 * width),
      y: this.getRandom(0, 0.125 * height),
    };
    return [p0, p1, p2, p3];
  },
  updatePath(data, factor) {
    const p0 = data[0];
    const p1 = data[1];
    const p2 = data[2];
    const p3 = data[3];
    const t = factor.t;

    /*计算多项式系数 （下同）*/
    const cx1 = 3 * (p1.x - p0.x);
    const bx1 = 3 * (p2.x - p1.x) - cx1;
    const ax1 = p3.x - p0.x - cx1 - bx1;

    const cy1 = 3 * (p1.y - p0.y);
    const by1 = 3 * (p2.y - p1.y) - cy1;
    const ay1 = p3.y - p0.y - cy1 - by1;

    const x = ax1 * (t * t * t) + bx1 * (t * t) + cx1 * t + p0.x;
    const y = ay1 * (t * t * t) + by1 * (t * t) + cy1 * t + p0.y;
    return {
      x,
      y,
    };
  },
  bubbleAnimate() {
    // let width = this.data.width;
    let height = this.data.height;
    Object.keys(queue).forEach((key) => {
      const anmationData = queue[+key];
      const { x, y } = this.updatePath(
        anmationData.pathData,
        anmationData.factor
      );
      const speed = anmationData.factor.speed;
      anmationData.factor.t += speed;
      var curWidth = 30;
      curWidth = (height - y) / 1.5;
      curWidth = Math.min(30, curWidth);
      var curAlpha = anmationData.opacity;
      curAlpha = y / height;
      curAlpha = Math.min(1, curAlpha);
      ctx.globalAlpha = curAlpha;
      ctx.drawImage(anmationData.image, x, y, curWidth, curWidth);
      if (anmationData.factor.t > 1) {
        delete queue[anmationData.id];
      }
    });
    ctx.draw();
    if (Object.keys(queue).length > 0) {
      timer_4 = setTimeout(() => {
        this.bubbleAnimate();
      }, 20);
    } else {
      clearTimeout(timer_4);
      ctx.draw(); // 清空画面
    }
  },
  //跳转举报
  liveReportBtn() {
    let that = this;
    this.setData({
      pauseBol: false,
    });
    setTimeout(function () {
      wx.navigateTo({
        url:
          "/packageD/directSeeding/liveReport/liveReport?id=" +
          that.data.room_id,
      });
    }, 500);
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let language = wx.getStorageSync("langIndex");
    this.setData({ language: language.en });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log('onshow:Sssssssssssssssssssssssss');
    this.data.activityDataBtnBol = false;
    this.data.roomMemberBtnBol = false;
    this.data.catMessagebol = true;
    this.setData({
      pauseBol: true,
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    // 清理定时器
    // console.log('onhide,clearInterval',this.data.smallWindowIn)
    if(!this.data.smallWindowIn){
      // console.log('clearInterval,直播不是在小窗，清除定时器')
      clearInterval(this.data.rewardTimeOut);
      this.data.rewardTimeOut = null;
    }else{
      console.log('直播在小窗，不清除定时器');
    }
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    //推出登录
    this.quitGroup();
    this.quitroom();
    setTimeout(() => {
      this.logout();
    }, 80);
    clearTimeout(timer);
    clearTimeout(timer_1);
    if (this.data.pkTimer) {
      // console.log('clearInterval')
      clearInterval(this.data.pkTimer);
      this.data.pkTimer = null;
    }
  },
  quitroom() {
    let urlStr = app.getNetAddresss("plugin.room.frontend.live.quit-room");
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: {
        room_id: this.data.room_id,
      },
      success: function (resdata) {
        var res = resdata.data;
        if (res.result != 1) {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res.msg);
      },
    });
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareTimeline: function () {
    var value = wx.getStorageSync("yz_uid");
    var mid = "";
    let shareImg = this.data.roomData.cover;
    if (value) {
      mid = value;
    }
    if (this.data.playerType == "live") {
      let json = {
        title:
          "欢迎进入" +
          this.data.roomData.nickname +
          "的" +
          this.data.roomData.title +
          "直播间！",
        path:
          "/packageD/directSeeding/livePage/livePage?id=" +
          this.data.room_id +
          "&playerType=live" +
          "&mid=" +
          mid,
      };
      if (shareImg) {
        json.imageUrl = shareImg;
      }
      return json;
    } else if (this.data.playerType == "video") {
      let url =
        "id=" +
        this.data.room_id +
        "&playerType=video&backid=" +
        this.data.backid +
        "&mid=" +
        mid;
      if (this.data.memberid) {
        url =
          "id=" +
          this.data.room_id +
          "&playerType=video&backid=" +
          this.data.backid +
          "&memberid=" +
          this.data.memberid +
          "&mid=" +
          mid;
      }
      let json = {
        title:
          "欢迎进入" +
          this.data.roomData.nickname +
          "的" +
          this.data.roomData.title +
          "直播间！",
        query: url,
      };
      if (shareImg) {
        json.imageUrl = shareImg;
      }
      return json;
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var value = wx.getStorageSync("yz_uid");
    var mid = "";
    let shareImg = this.data.roomData.cover;
    if (value) {
      mid = value;
    }
    if (this.data.playerType == "live") {
      let json = {
        title:
          "欢迎进入" +
          this.data.roomData.nickname +
          "的" +
          this.data.roomData.title +
          "直播间！",
        path:
          "/packageD/directSeeding/livePage/livePage?id=" +
          this.data.room_id +
          "&playerType=live" +
          "&mid=" +
          mid,
      };
      if(this.options.newMedia && this.options.newMedia==1){
        json.path = json.path+"&newMedia=1";
      }
      if (shareImg) {
        json.imageUrl = shareImg;
      }
      console.log(json);
      return json;
    } else if (this.data.playerType == "video") {
      let url =
        "/packageD/directSeeding/livePage/livePage?id=" +
        this.data.room_id +
        "&playerType=video&backid=" +
        this.data.backid +
        "&mid=" +
        mid;
      if (this.data.memberid) {
        url =
          "/packageD/directSeeding/livePage/livePage?id=" +
          this.data.room_id +
          "&playerType=video&backid=" +
          this.data.backid +
          "&memberid=" +
          this.data.memberid +
          "&mid=" +
          mid;
      }
      let json = {
        title:
          "欢迎进入" +
          this.data.roomData.nickname +
          "的" +
          this.data.roomData.title +
          "直播间！",
        path: url,
      };
      if(this.options.newMedia && this.options.newMedia==1){
        json.path = json.path+"&newMedia=1";
      }
      if (shareImg) {
        json.imageUrl = shareImg;
      }
      console.log(json);
      return json;
    }
  },
  /**
   * 将焦点给到 input（在真机上不能获取input焦点）
   */
  //清空聊天
  clearSend() {
    this.data.catMessagebol = true;
    this.setData({
      inputInfo: "",
    });
  },
  //发送聊天
  sendBtn() {
    
    if (this.data.room_ban) {
      wx.showToast({
        icon: "none",
        title: "您已经被禁言",
        duration: 1500,
      });
      return;
    }
    if (this.data.inputInfo) {
      this.setData({
        shade: false,
        mainCommentShow: false,
      });
      //发送普通聊天
      // this.sendmessage(this.data.inputInfo)
      if (this.data.catMessagebol) {
        this.catMessage("text", this.data.inputInfo);
      } else {
        wx.showToast({
          icon: "none",
          title: "聊天正在发送中......",
          duration: 1500,
        });
      }
      this.data.catMessagebol = false;
    } else {
      wx.showToast({
        icon: "none",
        title: "发送消息不能为空",
        duration: 1500,
      });
      this.setData({
        chatInputBottom:0
      });
    }
  },
  //创建聊天模版
  catMessage(type, text) {
    let that = this;
    let messageData = {};
    let Json = {
      memberId: this.data.roomData.userID ? this.data.roomData.userID : "",
      nickName: this.data.roomData.userNickname
        ? this.cutNameLimit(this.data.roomData.userNickname)
        : "",
      memberAvatar: this.data.roomData.userAvatar
        ? this.data.roomData.userAvatar
        : "",
      memberLevel: this.data.roomData.member_level
        ? this.data.roomData.member_level
        : 0,
      memberLevelName: this.data.roomData.member_level_name
        ? this.data.roomData.member_level_name
        : 0,
      text: text ? text : "",
    };
    switch (type) {
    case "text":
      messageData = {
        to: that.data.roomData.groupId,
        conversationType: TIM.TYPES.CONV_GROUP,
        payload: {
          data: "自定义文本", // 用于标识该类型消息
          description: JSON.stringify(Json),
          extension: "customText",
        },
      };
      break;
    }
    let message = that.data.tim.createCustomMessage(messageData);
    let promise = that.data.tim.sendMessage(message);
    promise
      .then(function (imResponse) {
        // 发送成功
        if (type == "text") {
          console.log(imResponse);
          let messageList = that.data.messageList;
          messageList.push(Json);
          that.setData({
            messagesTop: messageList.length * 1000,
            messageList,
          });
          that.clearSend();
          that.newMedia(6);
        }
      })
      .catch(function (imError) {
        // 发送失败
        if (type == "text") {
          that.clearSend();
        }
        wx.showToast({
          icon: "none",
          title: "聊天发送失败:::" + imError,
          duration: 1500,
        });
        console.warn("sendMessage error:", imError);
      });
  },
  sendmessage(data) {
    let that = this;
    let message = that.data.tim.createTextMessage({
      to: that.data.roomData.groupId,
      conversationType: TIM.TYPES.CONV_GROUP,
      payload: {
        text: data,
      },
    });
    // 2. 发送消息
    let promise = that.data.tim.sendMessage(message);
    promise
      .then(function (imResponse) {
        // 发送成功
        console.log(imResponse);
        let messageList = that.data.messageList;
        messageList.push({
          nick: that.data.roomData.userNickname,
          id: that.data.roomData.userID,
          text: data,
        });
        that.setData({
          messagesTop: messageList.length * 1000,
          messageList,
        });
        that.clearSend();
      })
      .catch(function (imError) {
        // 发送失败
        console.warn("sendMessage error:", imError);
        that.clearSend();
      });
  },
  cutNameLimit(_name) {
    if (_name.length > 8) {
      return _name.slice(0, 8) + "...";
    }
    return _name;
  },
  /**
   * input 失去焦点后将 input 的输入内容给到cover-view
   */
  blurInput(e) {
    this.setData({
      inputInfo: e.detail.value,
    });
  },
  bindfocusChatInput(e) {
    if(this.data.chatInputBottom != e.detail.height){
      this.setData({
        chatInputBottom: e.detail.height
      });
    }
  },
  showUserBtn() {
    if (
      this.data.anchorPopupData &&
      this.data.anchorPopupData.id &&
      !this.data.changeAnchor
    ) {
      this.setData({
        showUser: true,
        shade: true,
      });
    } else {
      this.getAnchorPopup();
    }
  },
  showUserCloseBtn() {
    this.setData({
      showUser: false,
      shade: false,
    });
  },
  showPosterBtn() {
    if(this.data.roomData.is_share_word != 1){
      this.setData({
        showPoster: true,
        shade: true,
      });
    } else{
      //开启了自定义分享语，显示弹窗设置
      this.setData({
        oldWord: this.data.diyPosterWord,
        showPosterWord: true
      });
    }
  },
  onClosePosterWord(){
    this.setData({
      showPosterWord:false
    });
  },
  changePosterWord(event){
    this.data.diyPosterWord = event.detail;
  },
  makePoster(){
    if (this.data.diyPosterWord==''||this.data.oldWord != this.data.diyPosterWord) {
      this.getAvaterInfo();
      this.setData({
        showPoster: true,
        shade: true,
      });
    }else {
      this.setData({
        showPoster: true
      });
    }
    this.setData({
      showPosterWord:false
    });
  },
  showPosterClose() {
    this.setData({
      showPoster: false,
      shade: false,
    });
  },
  showGoodLiftBtn() {
    this.setData({
      showGoodLift: true,
      shade: true,
    });
  },
  showGoodLiftCloseBtn() {
    this.setData({
      showGoodLift: false,
      shade: false,
    });
  },
  showGiftCloseBtn() {
    this.setData({
      showGift: false,
      shade: false,
    });
  },
  shadeClose() {
    if (this.data.showGoodLift) {
      this.setData({
        showGoodLift: false,
        shade: false,
      });
    }
    if (this.data.showGift) {
      this.setData({
        showGift: false,
        shade: false,
      });
    }
    if (this.data.mainCommentShow) {
      this.setData({
        mainCommentShow: false,
        shade: false,
      });
      this.clearSend();
    }
  },
  showGiftBtn() {
    if (this.data.giftListData.length > 0) {
      this.setData({
        showGift: true,
        shade: true,
      });
    } else {
      this.getGiftList();
    }
  },
  showactivityCloseBtn(e) {
    let index = e.currentTarget.dataset.index;
    this.setData({
      ["activityDataArray[" + index + "].activityData.showactivity"]: false,
    });
  },
  showactivityCloseBtn_1(e) {
    let index = e.currentTarget.dataset.index;
    this.setData({
      ["roomMemberContentArray[" +
      index +
      "].activityData.showactivity"]: false,
    });
  },
  showavticeFailBtn() {
    this.setData({
      showavticeFail: false,
      shade: false,
    });
  },
  mainCommentShowBtn() {
    if (this.data.imReadly || this.data.sendMessageReadly) {
      wx.showToast({
        icon: "none",
        title: "聊天加载中，请稍后发言",
        duration: 1500,
      });
      return;
    }
    if (this.data.room_ban) {
      wx.showToast({
        icon: "none",
        title: "您已经被禁言",
        duration: 1500,
      });
      return;
    }
    this.setData({
      mainCommentShow: true,
      shade: true,
    });
  },
  GetRTime() {
    let PKTime = this.data.startPKTime; //PK开始时间
    let NowTime = new Date(); //当前时间
    //后台给我的是10位 精确到秒的  所有下面我就除以了1000，不要小数点后面的
    let t = (NowTime.getTime() / 1000).toFixed(0) - PKTime;
    //如果后台给的是毫秒 上面不用除以1000  下面的计算时间也都要除以1000 这里我去掉1000了
    let d = Math.floor(t / 60 / 60 / 24); //天 var d=Math.floor(t/1000/60/60/24)
    let h = Math.floor((t / 60 / 60) % 24); //时 var h=Math.floor(t/1000/60/60%24)
    let m = Math.floor((t / 60) % 60); //分 var m=Math.floor(t/1000/60%60)
    let s = Math.floor(t % 60); //秒 var s=Math.floor(t/1000%60)
    if (parseInt(d) < 10) d = "0" + d;
    if (parseInt(h) < 10) h = "0" + h;
    if (parseInt(m) < 10) m = "0" + m;
    if (parseInt(s) < 10) s = "0" + s;
    if (parseInt(d) >= 1) {
      this.setData({
        PKTimed: `${d}:${h}:${m}:${s}`
      });
    } else {
      this.setData({
        PKTimed: `${h}:${m}:${s}`
      });
    }
  },
  getAvaterInfo() {
    let statusText =
      this.data.postData.status == 2
        ? "预告"
        : this.data.postData.status == 3
          ? "直播中 "
          : "回放";
    const ctx = wx.createCanvasContext("myCanvas");
    // 画banner图
    ctx.fillStyle = "#FFFFFF";
    ctx.fillRect(0, 0, this.data.canvasWidth, this.data.canvasHeight);
    let headWH = 56 * canvasDpr * unit;
    {
      let avatarurl_width = headWH; //绘制的头像宽度
      let avatarurl_heigth = headWH; //绘制的头像高度
      let avatarurl_x = 215 * canvasDpr * unit; //绘制的头像在画布上的位置
      let avatarurl_y = 23 * canvasDpr * unit; //绘制的头像在画布上的位置
      ctx.save();
      ctx.beginPath(); //开始绘制
      //先画个圆   前两个参数确定了圆心 （x,y） 坐标  第三个参数是圆的半径  四参数是绘图方向  默认是false，即顺时针
      ctx.arc(
        avatarurl_width / 2 + avatarurl_x,
        avatarurl_heigth / 2 + avatarurl_y,
        avatarurl_width / 2,
        0,
        Math.PI * 2,
        false
      );
      ctx.clip(); //画好了圆 剪切  原始画布中剪切任意形状和尺寸。一旦剪切了某个区域，则所有之后的绘图都会被限制在被剪切的区域内 这也是我们要save上下文的原因
      if (this.data.postData.shop_logo) {
        ctx.drawImage(
          this.data.postData.shop_logo,
          avatarurl_x,
          avatarurl_y,
          avatarurl_width,
          avatarurl_heigth
        ); // 推进去图片，必须是https图片
      }
      ctx.restore(); //恢复之前保存的绘图上下文 恢复之前保存的绘图上下午即状态 还可以继续绘制
    }
    ctx.setFontSize(13 * canvasDpr);
    ctx.setFillStyle("#000");
    ctx.fillText(
      this.data.postData.shop_name,
      296 * canvasDpr * unit,
      60 * canvasDpr * unit
    );
    this.drawImg(
      ctx,
      560 * canvasDpr * unit,
      440 * canvasDpr * unit,
      this.data.postData.cover,
      this.data.postData.imgData.width,
      this.data.postData.imgData.height,
      30 * canvasDpr * unit,
      98 * canvasDpr * unit
    );
    // ctx.drawImage(this.data.postData.cover, 30 * unit, 98 * unit, 560 * unit, 440 * unit);
    {
      let x = 437 * canvasDpr * unit,
        y = 117 * canvasDpr * unit,
        w = 127 * canvasDpr * unit,
        h = 42 * canvasDpr * unit,
        fillColor = "#ff7200",
        r = 10 * canvasDpr;
      // if (2 * r > w || 2 * r > h) {
      // 	return false;
      // }
      ctx.save();
      ctx.translate(x, y);
      //绘制圆角矩形的各个边
      this.drawRoundRectPath(ctx, w, h, r);
      ctx.fillStyle = fillColor;
      ctx.fill();
      ctx.restore();
      ctx.setFillStyle("#fff");
      ctx.setFontSize(14 * canvasDpr);
      if (statusText.length == 2) {
        ctx.fillText(
          statusText,
          474 * canvasDpr * unit,
          148 * canvasDpr * unit
        );
      } else {
        ctx.fillText(
          statusText,
          460 * canvasDpr * unit,
          148 * canvasDpr * unit
        );
      }
    }
    let headWH_2 = 42 * canvasDpr * unit;
    {
      let avatarurl_width = headWH_2; //绘制的头像宽度
      let avatarurl_heigth = headWH_2; //绘制的头像高度
      let avatarurl_x = 52 * canvasDpr * unit; //绘制的头像在画布上的位置
      let avatarurl_y = 117 * canvasDpr * unit; //绘制的头像在画布上的位置
      ctx.save();
      ctx.beginPath(); //开始绘制
      //先画个圆   前两个参数确定了圆心 （x,y） 坐标  第三个参数是圆的半径  四参数是绘图方向  默认是false，即顺时针
      ctx.arc(
        avatarurl_width / 2 + avatarurl_x,
        avatarurl_heigth / 2 + avatarurl_y,
        avatarurl_width / 2,
        0,
        Math.PI * 2,
        false
      );
      ctx.clip(); //画好了圆 剪切  原始画布中剪切任意形状和尺寸。一旦剪切了某个区域，则所有之后的绘图都会被限制在被剪切的区域内 这也是我们要save上下文的原因
      ctx.drawImage(
        this.data.postData.avatar,
        avatarurl_x,
        avatarurl_y,
        avatarurl_width,
        avatarurl_heigth
      ); // 推进去图片，必须是https图片
      ctx.restore(); //恢复之前保存的绘图上下文 恢复之前保存的绘图上下午即状态 还可以继续绘制
    }

    {
      let text = this.data.postData.nickname; //这是要绘制的文本';
      let chr = text.split(""); //这个方法是将一个字符串分割成字符串数组
      let temp = "";
      let row = [];
      ctx.setFontSize(28 * canvasDpr * unit);
      ctx.setFillStyle("#fff");
      for (let a = 0; a < chr.length; a++) {
        if (ctx.measureText(temp).width < 160 * canvasDpr) {
          temp += chr[a];
        } else {
          a--; //这里添加了a-- 是为了防止字符丢失，效果图中有对比
          row.push(temp);
          temp = "";
        }
      }
      row.push(temp); //如果数组长度大于2 则截取前两个
      if (row.length > 2) {
        let rowCut = row.slice(0, 2);
        let rowPart = rowCut[1];
        let test = "";
        let empty = [];
        for (let a = 0; a < rowPart.length; a++) {
          if (ctx.measureText(test).width < 306 * canvasDpr * unit) {
            test += rowPart[a];
          } else {
            break;
          }
        }
        empty.push(test);
        let group = empty[0] + "...";
        //这里只显示两行，超出的用...表示
        rowCut.splice(1, 1, group);
        row = rowCut;
      }
      for (let b = 0; b < row.length; b++) {
        ctx.fillText(
          row[b],
          108 * canvasDpr * unit,
          146 * canvasDpr * unit + b * (28 * canvasDpr * unit)
        );
      }
      ctx.restore(); //恢复之前保存的绘图上下文 恢复之前保存的绘图上下午即状态 还可以继续绘制
    }

    // ctx.setFontSize(13)
    // ctx.setFillStyle("#fff")
    // ctx.fillText(this.data.postData.nickname, 108 * unit, 146 * unit)
    ctx.save();
    {
      let text = this.data.postData.title; //这是要绘制的文本';
      let chr = text.split(""); //这个方法是将一个字符串分割成字符串数组
      let temp = "";
      let row = [];
      ctx.setFontSize(28 * canvasDpr * unit);
      ctx.setFillStyle("#333333");
      for (let a = 0; a < chr.length; a++) {
        if (ctx.measureText(temp).width < 160 * canvasDpr) {
          temp += chr[a];
        } else {
          a--; //这里添加了a-- 是为了防止字符丢失，效果图中有对比
          row.push(temp);
          temp = "";
        }
      }
      row.push(temp); //如果数组长度大于2 则截取前两个
      if (row.length > 2) {
        let rowCut = row.slice(0, 2);
        let rowPart = rowCut[1];
        let test = "";
        let empty = [];
        for (let a = 0; a < rowPart.length; a++) {
          if (ctx.measureText(test).width < 306 * canvasDpr * unit) {
            test += rowPart[a];
          } else {
            break;
          }
        }
        empty.push(test);
        let group = empty[0] + "...";
        //这里只显示两行，超出的用...表示
        rowCut.splice(1, 1, group);
        row = rowCut;
      }
      for (let b = 0; b < row.length; b++) {
        ctx.fillText(
          row[b],
          41 * canvasDpr * unit,
          620 * canvasDpr * unit + b * (28 * canvasDpr * unit)
        );
      }
      ctx.restore(); //恢复之前保存的绘图上下文 恢复之前保存的绘图上下午即状态 还可以继续绘制
      ctx.setFontSize(12 * canvasDpr);
      ctx.setFillStyle("#ff7200");
      ctx.fillText(
        "直播时间 " + this.data.postData.live_time,
        36 * canvasDpr * unit,
        760 * canvasDpr * unit
      );
    }
    let headWH_3 = 48 * canvasDpr * unit;
    {
      let avatarurl_width = headWH_3; //绘制的头像宽度
      let avatarurl_heigth = headWH_3; //绘制的头像高度
      let avatarurl_x = 35 * canvasDpr * unit; //绘制的头像在画布上的位置
      // let avatarurl_y = 763 * canvasDpr * unit; //绘制的头像在画布上的位置
      let avatarurl_y = 787 * canvasDpr * unit; //绘制的头像在画布上的位置
      ctx.save();
      ctx.beginPath(); //开始绘制
      //先画个圆   前两个参数确定了圆心 （x,y） 坐标  第三个参数是圆的半径  四参数是绘图方向  默认是false，即顺时针
      ctx.arc(
        avatarurl_width / 2 + avatarurl_x,
        avatarurl_heigth / 2 + avatarurl_y,
        avatarurl_width / 2,
        0,
        Math.PI * 2,
        false
      );
      ctx.clip(); //画好了圆 剪切  原始画布中剪切任意形状和尺寸。一旦剪切了某个区域，则所有之后的绘图都会被限制在被剪切的区域内 这也是我们要save上下文的原因
      ctx.drawImage(
        this.data.postData.m_avatar,
        avatarurl_x,
        avatarurl_y,
        avatarurl_width,
        avatarurl_heigth
      ); // 推进去图片，必须是https图片
      ctx.restore(); //恢复之前保存的绘图上下文 恢复之前保存的绘图上下午即状态 还可以继续绘制
    }

    {
      let text = this.data.roomData.is_share_word == 1&&this.data.diyPosterWord!='' ? this.data.diyPosterWord:(this.data.postData.m_nickname + "的分享");//这是要绘制的文本';
      let chr = text.split(""); //这个方法是将一个字符串分割成字符串数组
      let temp = "";
      let row = [];
      ctx.setFontSize(28 * canvasDpr * unit);
      ctx.setFillStyle("#666666");
      for (let a = 0; a < chr.length; a++) {
        // 160
        if (ctx.measureText(temp).width < 230 * canvasDpr) {
          temp += chr[a];
        } else {
          a--; //这里添加了a-- 是为了防止字符丢失，效果图中有对比
          row.push(temp);
          temp = "";
        }
      }
      row.push(temp); //如果数组长度大于2 则截取前两个
      if (row.length > 2&&this.data.roomData.is_share_word != 1) {
        let rowCut = row.slice(0, 2);
        let rowPart = rowCut[1];
        let test = "";
        let empty = [];
        for (let a = 0; a < rowPart.length; a++) {
          if (ctx.measureText(test).width < 306 * canvasDpr * unit) {
            test += rowPart[a];
          } else {
            break;
          }
        }
        empty.push(test);
        let group = empty[0] + "...";
        //这里只显示两行，超出的用...表示
        rowCut.splice(1, 1, group);
        row = rowCut;
      }
      for (let b = 0; b < row.length; b++) {
        // ctx.fillText(
        //   row[b],
        //   94 * canvasDpr * unit,
        //   796 * canvasDpr * unit + b * (28 * canvasDpr * unit)
        // );
        ctx.fillText(
          row[b],
          94 * canvasDpr * unit,
          820 * canvasDpr * unit + b * (28 * canvasDpr * unit)
        );
      }
      ctx.restore(); //恢复之前保存的绘图上下文 恢复之前保存的绘图上下午即状态 还可以继续绘制
    }

    // ctx.setFontSize(13)
    // ctx.setFillStyle("#666666")
    // ctx.fillText(this.data.postData.m_nickname + '的分享', 94 * unit, 796 * unit)
    ctx.save();
    ctx.drawImage(
      this.data.postData.qr_code,
      408 * canvasDpr * unit,
      561 * canvasDpr * unit,
      180 * canvasDpr * unit,
      180 * canvasDpr * unit
    );
    ctx.restore(); //恢复之前保存的绘图上下文 恢复之前保存的绘图上下午即状态 还可以继续绘制
    ctx.setFontSize(12 * canvasDpr);
    ctx.setFillStyle("#333");
    ctx.fillText(
      "长按保存图片",
      430 * canvasDpr * unit,
      780 * canvasDpr * unit
    );
    ctx.draw(false, this.toimage());
  },
  drawRoundRectPath(cxt, width, height, radius) {
    cxt.beginPath(0);
    //从右下角顺时针绘制，弧度从0到1/2PI
    cxt.arc(width - radius, height - radius, radius, 0, Math.PI / 2);

    //矩形下边线
    cxt.lineTo(radius, height);

    //左下角圆弧，弧度从1/2PI到PI
    cxt.arc(radius, height - radius, radius, Math.PI / 2, Math.PI);

    //矩形左边线
    cxt.lineTo(0, radius);

    //左上角圆弧，弧度从PI到3/2PI
    cxt.arc(radius, radius, radius, Math.PI, (Math.PI * 3) / 2);

    //上边线
    cxt.lineTo(width - radius, 0);

    //右上角圆弧
    cxt.arc(width - radius, radius, radius, (Math.PI * 3) / 2, Math.PI * 2);

    //右边线
    cxt.lineTo(width, height - radius);
    cxt.closePath();
  },
  drawImg(ctx, cWidth, cHeight, imgPath, imgWidth, imgHeight, x, y) {
    console.log("cWidth", cWidth);
    console.log("cHeight", cHeight);
    console.log("imgWidth", imgWidth);
    console.log("imgHeight", imgHeight);
    let dWidth = cWidth / imgWidth; // canvas与图片的宽度比例
    let dHeight = cHeight / imgHeight; // canvas与图片的高度比例
    if (
      (imgWidth > cWidth && imgHeight > cHeight) ||
      (imgWidth < cWidth && imgHeight < cHeight)
    ) {
      if (dWidth > dHeight) {
        ctx.drawImage(
          imgPath,
          0,
          (imgHeight - cHeight / dWidth) / 2,
          imgWidth,
          cHeight / dWidth,
          x,
          y,
          cWidth,
          cHeight
        );
      } else {
        ctx.drawImage(
          imgPath,
          (imgWidth - cWidth / dHeight) / 2,
          0,
          cWidth / dHeight,
          imgHeight,
          x,
          y,
          cWidth,
          cHeight
        );
      }
    } else {
      if (imgWidth < cWidth) {
        ctx.drawImage(
          imgPath,
          0,
          (imgHeight - cHeight / dWidth) / 2,
          imgWidth,
          cHeight / dWidth,
          x,
          y,
          cWidth,
          cHeight
        );
      } else {
        ctx.drawImage(
          imgPath,
          (imgWidth - cWidth / dHeight) / 2,
          0,
          cWidth / dHeight,
          imgHeight,
          x,
          y,
          cWidth,
          cHeight
        );
      }
    }
  },
  toimage() {
    // wx.hideLoading()
    this.setData({
      showBtn: true,
    });
    let that = this;
    setTimeout(() => {
      wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        width: this.data.canvasWidth,
        height: this.data.canvasHeight,
        destWidth: this.data.canvasWidth * 4,
        destHeight: this.data.canvasHeight * 4,
        canvasId: "myCanvas",
        success: function (res) {
          console.log(res);
          var tempFilePath = res.tempFilePath;
          that.setData({
            ithumb: tempFilePath,
            loadingImg: false,
          });
        },
        fail: function (res) {
          console.log(res);
        },
      });
    }, 1500);
  },
  saveShareImg: function () {
    wx.showLoading({
      title: "保存中",
    });
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: this.data.canvasWidth,
      height: this.data.canvasHeight,
      destWidth: this.data.canvasWidth * 4,
      destHeight: this.data.canvasHeight * 4,
      canvasId: "myCanvas",
      success: function (res) {
        console.log(res);
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success(result) {
            wx.showToast({
              title: "图片保存成功",
              icon: "success",
              duration: 2000,
            });
            wx.hideLoading();
          },
          fail: (res) => {
            wx.hideLoading();
          },
        });
      },
    });
  },
  giftSelsectBtn(e) {
    let num = e.currentTarget.dataset.type;
    if (num == 1) {
      this.setData({
        activeNum: 1,
      });
    } else if (num == 2) {
      this.setData({
        activeNum: 2,
      });
    } else if (num == 3) {
      this.setData({
        activeNum: 3,
      });
    }
  },
  backRightBtn() {
    wx.navigateBack({
      delta: 1,
      fail() {
        wx.navigateTo({
          url: "/packageG/index/index",
        });
      },
    });
  },
  cloneLuckDraw(){
    this.setData({
      luck_number: 0
    });
  },
  gotoLuckDraw(){
    wx.navigateTo({
      url: '/packageH/newDraw/luckyDraw/luckyDraw'
    });
  },
  cloneADbtn(e){
    let datas = e.currentTarget.dataset;
    if(datas.tag == '1'){
      this.setData({
        isShowADLook: false
      });
    }
    if(datas.tag == '2'){
      this.setData({
        isShowADPut: false
      });
    }
  },
  gotoUrl(e){
    let datas = e.currentTarget.dataset;
    if (datas.name == "advertisingPutAD") {
      //投放广告按钮
      if (!datas.iser) {
        wx.navigateTo({url: '/packageH/Advertising/advertisingApply/advertisingApply' });//还不是广告主，跳转申请页
      } else {
        wx.navigateTo({url: '/packageH/Advertising/advertisingPutAD/advertisingPutAD?tag=live&id='+ datas.id });
      }
      return;
    }
    wx.navigateTo({url: '/packageH/Advertising/advertisingList/advertisingList?tag=live&id='+ datas.id });
  },
  gotoPKLiver(e){
    let datas = e.currentTarget.dataset;
    if(datas.id) wx.navigateTo({url:"/packageD/directSeeding/livePage/livePage?id=" + datas.id +"&playerType=live",}); 
  },
  giftEffectsTimer(){
    //打赏礼物特效定时器
    let timer = Number(this.data.specialList[0].effect_time)>0?Number(this.data.specialList[0].effect_time)*1000:2000; //特效周期，后台设置，单位/秒

    this.data.giftEffectsTime = setTimeout(() => {
      this.data.specialList.splice(0, 1); //特效gif周期到了，删除
      this.setData({
        specialList: this.data.specialList
      });
      if (this.data.specialList.length > 0) {
        this.giftEffectsTimer();
      } else {
        clearTimeout(this.data.giftEffectsTime);
      }
    }, timer);
  },

  //新媒体插件
  newMedia(behavioral){
    //behavioral 1点赞，2关注，3阅读，4转发，5收藏，6评论
    if(!this.options.newMedia || this.options.newMedia!=1) return;
    let urlStr = app.getNetAddresss("plugin.new-media-advertising.frontend.media-advertisingt.root-behavioral-reward");
    app._getNetWork({
      url: urlStr,
      data: {behavioral,advertisingt_id:this.options.id},
      success: (resdata) => {}
    });
  }

});
